I’d like to declare a generic class Simple where a method called Addition would take two generic variables and add them together using + operator. I thought I could accomplish this by giving class Simple the following constraint:
class Simple<T> where T: int
{
public T Addition(T firstInt, T secondInt)
{
return firstInt + secondInt;
}
}
I suspect error has something to do with generics only having the following five types of constraints – ClassName, class, struct,InterfaceName, new()? Thus, why don’t generics also support StructureName constraint type? That way we would be able to apply arithmetic operators on generic variables?!
thanx
A
StructNameconstraint wouldn’t make sense, since you cannot inherit from value types.If you had something like
class Simple<T> where T : intyou could only instantiateSimple<T>withT = int, no type inherits fromintor any other value type for that matter.C# (the CLR) lacks what other languages know as type classes, one popular mechanism to handle operator overloading without hard-coded compiler mechanics (like in C#).