Arithmetic operator overloading for a generic class in C#

Triynko picture Triynko · Apr 16, 2009 · Viewed 25.8k times · Source

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?

Answer

Daniel Schaffer picture Daniel Schaffer · Apr 16, 2009

I think the best you'd be able to do is use IConvertible as a constraint and do something like:

 public static operator T +(T x, T y)
    where T: IConvertible
{
    var type = typeof(T);
    if (type == typeof(String) ||
        type == typeof(DateTime)) throw new ArgumentException(String.Format("The type {0} is not supported", type.FullName), "T");

    try { return (T)(Object)(x.ToDouble(NumberFormatInfo.CurrentInfo) + y.ToDouble(NumberFormatInfo.CurrentInfo)); }
    catch(Exception ex) { throw new ApplicationException("The operation failed.", ex); }
}

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.