Friday, 6 September 2013

Generic classes - when to use and why

Generic classes - when to use and why

i understand what they are, I'm just wondering when is the best time to
use them.
My first thought was - when we are building a (static) utility class which
should perform certain operations on different data types. Ergo, it is a
good practice to use generic methods to avoid numerous overloads of a
certain method? Please comment on this.
I have a small example class. It's just for the sake of an example.
public static class Math<T> where T : operator +, operator -
{
public static T Add(T a1, T a2)
{
return a1+a2;
}
public static T Subtract(T a1, T a2)
{
return a1 - a2;
}
}
Would this be a good usage of generic classes and methods, e.g I wish to
add and subtract ints, doubles.. etc.. with the minimum amount of code ?
Why won't this compile? I've tried this as well as modifying the class
signature:
public static class Math<T> where T : struct
I understand that I must specify whether the Type parameter is of
reference or of value type. I did that by specifying that T must be
constrained as a value type, so why am I still getting error that the
operator + and/or - cannot be applied to T (which should specifically be a
value type)

No comments:

Post a Comment