Can someone explain why this won’t work? I was trying to be able to add two values regardless of the numeric type.
public static T Add<T> (T number1, T number2)
{
return number1 + number2;
}
When I compile this, I get the following error:
Operator '+' cannot be applied to operands of type 'T' and 'T'
There is no generic constraint that allows you to enforce operator overload. You may take a look at the following library. Alternatively if you are using .NET 4.0 you could use the
dynamickeyword:Obviously this doesn’t apply any compile time safety which is what generics are meant for. The only way to apply compile time safety is to enforce generic constraints. And for your scenario there is no constraint available. It’s only a trick to cheat the compiler. If the caller of the Add method doesn’t pass types that work with the + operator the code will throw an exception at runtime.