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?
public static T Add<T>(T a, T b) { //Implementation goes here }
. This could be used likeFoo x = new Bar(); Foo y = new MyClass(); Foo sum = Foo.Add(x, y);
. – Dailey