Hi
Dot net 2.0 has introduced generics, which is very useful in many situations. We can introduce some generic methods into the non generic types. This brings power of generics to class with requiring the class itself to me parameterized.
To expand on that I will take an example of a simple function Minimum() which accepts to integer Values and returns the minimum of the two.
public int Minimum(int val1, int val2)
{
return (val2 < val1) ? val1 : val2;
}
There is no problem till we use the function through out the application (or through multiple applications). But the problem starts when we want the same function for multiple data types (Say Double, Decimal, Int64 etc…). There are many approaches to solve the problem.
One approach can be to create specific function for all the different data types like MinimumString, MinimumInt etc. Doing this will bloat the namespace and hence this approach is not good.
Another approach can be to remove the type safety of the function. I mean we can change the input parameter to object type and remove any type safety to the method. But this option is also not useful as it remove any type safety for the method.
Last option is to provide multiple overload of the same function to provide the functionality. This method is the best among the other motioned, but it’s still not the best strategy. In this case we will need to create multiple functions for each data type.
This problem can happen with any function when we try to expand it for more general use. This is the place where the generics can help us a lot. Let see how we can use the generics method in this case.
public T Minimum<T>(T value1, T value2) where T : IComparable
{
T ReturnValue = value2;
if (value2.CompareTo(value1) < 0)
ReturnValue = value1;
return ReturnValue;
}
This function can be used in the following way
double min = Minimum<double>(3.9999, 3.998);
int min = Minimum<int>(3, 4);
This gives us an unbloated types safe function which can be used to get the minium value. The functiobn can accept more than one datatype in its signature. The input types, the return type and the type used in the function can be provided easily by the function calling the method.
Hope this helps
Thanks
Vikram