C# Adding two Generic Values

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 dynamic keyword:

public static T Add<T>(T number1, T number2)
{
    dynamic a = number1;
    dynamic b = number2;
    return a + b;
}

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.

Leave a Comment