Understanding Generics—The Lack of Operator Constraints

Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio


Jump to: navigation, search
CSharp-Online.NET:Articles
C# Articles

Understanding Generics

© 2006 Andrew Troelsen

The Lack of Operator Constraints

When you are creating generic methods, it may come as a surprise to you that it is a compiler error to apply any C# operators (+, -, *, ==, etc.) on the type parameters. As an example, I am sure you could imagine the usefulness of a class that can Add(), Subtract(), Multiply(), and Divide() generic types:

// Compiler error! Cannot apply
// operators to type parameters!
public class BasicMath<T>
{
   public T Add(T arg1, T arg2)
   { return arg1 + arg2; }
   public T Subtract(T arg1, T arg2)
   { return arg1 - arg2; }
   public T Multiply(T arg1, T arg2)
   { return arg1 * arg2; }
   public T Divide(T arg1, T arg2)
   { return arg1 / arg2; }
}

Sadly, the preceding BasicMath<T> class will not compile. While this may seem like a major restriction, you need to remember that generics are generic. Of course, the System.Int32 type can work just fine with the binary operators of C#. However, for the sake of argument, if <T> were a custom class or structure type, the compiler cannot assume it has overloaded the +, -, *, and / operators. Ideally, C# would allow a generic type to be constrained by supported operators, for example:

// Illustrative code only!
// This is not legal code under C# 2.0.
public class BasicMath<T> where T : operator +, operator -,
   operator *, operator /
{
   public T Add(T arg1, T arg2)
   { return arg1 + arg2; }
   public T Subtract(T arg1, T arg2)
   { return arg1 - arg2; }
   public T Multiply(T arg1, T arg2)
   { return arg1 * arg2; }
   public T Divide(T arg1, T arg2)
   { return arg1 / arg2; }
}

Alas, operator constraints are not supported under C# 2005.


Previous_Page_.gif Next_Page_.gif

Personal tools