0

Possible Duplicate:
Solution for overloaded operator constraint in .NET generics

I have the method

    public static T Add<T>(T x, T y) 
    {
        return x + y;
    }

and I obviosly get a compilation error because maybe the type T does not suppport the operator + . For example if I where to call the method as:

     Add<MyCar>(car1, car2);

It will not be possible to call that method because MyCar class does not have a definition for the + operator.

But it will make sence to call that method as:

    Add<Int32>(1,2);

So I remember I read long time ago that I had to place a where clause on the method in order to be able to compile it. It was somethind like:

    public static T Add<T>(T x, T y) where T: "implements + operator"
    {
        return x + y;
    }

But I do not remember the syntax.

Community
  • 1
  • 1
Tono Nam
  • 34,064
  • 78
  • 298
  • 470
  • 3
    http://lmajsfy.com/?q=generic+type+math+operators – Steven Sep 26 '12 at 14:15
  • To my knowledge, C# generics do not allow for overloaded operators. This is discussed in more detail at http://stackoverflow.com/questions/5905563/c-sharp-generic-operators. – David W Sep 26 '12 at 14:16
  • Your syntax `where T : constaint` is correct, however there is no constraint for operators. See [Constraints on Type Parameters](http://msdn.microsoft.com/en-us/library/d5x73970.aspx) for a list of available constraints. – verdesmarald Sep 26 '12 at 14:18
  • 1
    You could convert the arguments to `dynamic`, if that is acceptable. – phipsgabler Sep 26 '12 at 14:22

0 Answers0