Consider the following code :-
Returns minimum between two integers.
int Min( int a, int b )
{
if (a < b) return a;
else return b;
}
let suppose you have objects or string then this will not work.To use this code, we need a different version of Min for each type of parameter we want to compare then developers think to use in the folllowing manner :-
Returns minimum between two objects.
object Min( object a, object b )
{
if (a < b) return a;
else return b;
}
But less than operator (<) is not defined for the generic object type.So we need to use a coomon interface to use ex:-Icomparable. like in the following manner :-
IComparable Min( IComparable a, IComparable b )
{
if (a.CompareTo( b ) < 0) return a;
else return b;
}
By this way problem has been solved but now there is a big issue.A caller of Min that passes two integers should make a type conversion from IComparable to int and may be it gives an exception. like :-
int a = 7, b = 16
int c = (int) Min( a, b );
but .net 2.0 solved the issue using Generics.
This is the generic version of MIN method.
T Min
{
if (a.CompareTo( b ) < 0) return a;
else return b;
}
Now you can call like in this manner :-
int a = 7 b = 16;
int c = Min
Happy to code.
0 comments:
Post a Comment