Arithmetic operator overloading for a generic class in C#

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.

Leave a Comment