3

I was making a generic method and was wondering if there is some way of adding a constraint to a generic type T, such that T has a certain operator, like +, +=, -, -=, etc.

public void TestAdd<T>(T t1, T t2)
{
    return t1 + t2;
}

Produces the following error text:

Operator '+' cannot be applied to operands of type 'T' and 'T'

I searched around on Google/SO for a while and couldn't really find anything related.

Daniel Imms
  • 47,944
  • 19
  • 150
  • 166
  • See: http://www.yoda.arachsys.com/csharp/genericoperators.html – Ani Feb 21 '13 at 05:41
  • This might help http://stackoverflow.com/questions/756954/arithmetic-operator-overloading-for-a-generic-class-in-c-sharp – Jigar Patel Feb 21 '13 at 05:43
  • 2
    possible duplicate of [Solution for overloaded operator constraint in .NET generics](http://stackoverflow.com/questions/147646/solution-for-overloaded-operator-constraint-in-net-generics) – Sergey Berezovskiy Feb 21 '13 at 05:51
  • Thanks lazyberezovsky, that answers it. Unfortunately it's not supported. Not going near his dynamic solution. – Daniel Imms Feb 21 '13 at 05:59

1 Answers1

1

I think this cannot be done

You can do it less fancy by :

interface IAddable { void Add(object item); }
...
public void TestAdd<T>(T t1, T t2) where T : IAddable
{
   return t1.Add(t2);
}
Benny
  • 207
  • 1
  • 7
  • My guess is he is trying to support built-in types such as int, double, decimal, etc. None of those would implement your custom interface. – Anthony Pegram Feb 21 '13 at 05:45
  • Yea, was trying to avoid a custom interface and see if there was native support for constraining based on the operators of the object. – Daniel Imms Feb 21 '13 at 05:49
  • 1
    Yeah I know, I'm afraid this is not supported, this was the closest alternative I could think of – Benny Feb 21 '13 at 06:05