I am trying to implement a generic operator like so:
class Foo
{
public static T operator +<T>(T a, T b)
{
// Do something with a and b that makes sense for operator + here
}
}
Really what I'm trying to do is gracefully handle inheritance. With a standard operator + in Foo, where T is instead "Foo", if anyone is derived from Foo (say Bar inherits Foo), then a Bar + Bar operation will still return a Foo. I was hoping to solve this with a generic operator +, but I just get a syntax error for the above (at the <) making me believe that such code is not legal.
Is there a way to make a generic operator?
No, you can't declare generic operators in C#.
Operators and inheritance don't really mix well.
If you want Foo + Foo to return a Foo and Bar + Bar to return a Bar, you will need to define one operator on each class. But, since operators are static, you won't get the benefits of polymorphism because which operator to call will be decided at compile-time:
Foo x = new Bar(); Foo y = new Bar(); var z = x + y; // calls Foo.operator+;
https://jonskeet.uk/csharp/miscutil/usage/genericoperators.html
static T Add<T>(T a, T b) {
//TODO: re-use delegate!
// declare the parameters
ParameterExpression paramA = Expression.Parameter(typeof(T), "a"),
paramB = Expression.Parameter(typeof(T), "b");
// add the parameters together
BinaryExpression body = Expression.Add(paramA, paramB);
// compile it
Func<T, T, T> add = Expression.Lambda<Func<T, T, T>>(body, paramA, paramB).Compile();
// call it
return add(a,b);
}
You can just define operator in a generic class Foo.
You can also create real generic operators, but C# compiler won't use them.
[System.Runtime.CompilerServices.SpecialName]
public static T op_Addition<T>(T a, T b) { ... }
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