Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Generic Operators

Tags:

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?

like image 591
Shirik Avatar asked May 06 '11 00:05

Shirik


3 Answers

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+; 
like image 130
R. Martinho Fernandes Avatar answered Dec 08 '22 00:12

R. Martinho Fernandes


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);       
}
like image 41
Rakoo Avatar answered Dec 08 '22 01:12

Rakoo


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) { ... }
like image 27
Ark-kun Avatar answered Dec 08 '22 00:12

Ark-kun