Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET interface/constraint for object that implements certain operators

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.

like image 308
Daniel Imms Avatar asked May 16 '26 01:05

Daniel Imms


1 Answers

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);
}
like image 136
Benny Avatar answered May 18 '26 15:05

Benny