Back to results for “Generics”
C# › Generics

Why can't you use operators like + directly on an unconstrained generic T?

Intermediate

Answer

Because the compiler doesn't know T supports the operator. You must constrain T (e.g. to INumber<T>) or pass a delegate/strategy that performs the operation.
// error without constraint: T r = a + b;
T Add<T>(T a, T b) where T : INumber<T> => a + b;
Real-world example Generic aggregation helpers require a numeric constraint to add values.