In C++, you can write code like this:
template<class T>
T Add(T lhs, T rhs)
{
return lhs + rhs;
}
But, you can't do something like this in C#:
public static T Add<T>(T x, T y) where T : operator+
{
return x + y;
}
Is there any reason why? I know it could be accomplished through reflection (generic Add
with objects and then run type checking over it all), but that's inefficient and doesn't scale well. So, again, why?
There is no inherent reason this could not exist. The way generic type constrains are implemented is through interface calls. If there were an interface that provided an operator+
this would work.
This interface would be required for all relevant types, though, to be as general as the C++ template-based analog.
Another issue would be that .NET has no multiple dispatch. The interface call would be asymmetric: a.Plus(b)
could mean something different than b.Plus(a)
. Equals
has the same problem, btw.
So this issue probably did not meet the "usefulness"-bar or the "cost/utility"-bar. This is not an issue of impossibility, but of practical concerns.
Proof that it is possible: ((dynamic)a) + ((dynamic)b)
.
The CLR doesn't natively support such constraints, and the C# design team evidently decided to support the same set of constraints as the CLR. Presumably both the CLR team and the C# team felt that the benefits of implementing such a feature didn't outweigh the costs of speccing, implementing, and testing it.
If you want to use a .NET language that does support such constraints, consider taking a look at F#.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With