Given a generic class definition like
public class ConstrainedNumber<T> : IEquatable<ConstrainedNumber<T>>, IEquatable<T>, IComparable<ConstrainedNumber<T>>, IComparable<T>, IComparable where T:struct, IComparable, IComparable<T>, IEquatable<T>
How can I define arithmetic operators for it?
The following does not compile, because the ‘+’ operator cannot be applied to types ‘T’ and ‘T’:
public static T operator +( ConstrainedNumber<T> x, ConstrainedNumber<T> y) { return x._value + y._value; }
The generic type ‘T’ is constrained with the ‘where’ keyword as you can see, but I need a constraint for number types that have arithmetic operators (IArithmetic?).
‘T’ will be a primitive number type such as int, float, etc. Is there a ‘where’ constraint for such types?
I think the best you’d be able to do is use
IConvertibleas a constraint and do something like:That won’t stop someone from passing in a String or DateTime though, so you might want to do some manual checking – but IConvertible should get you close enough, and allow you to do the operation.