How can I subtract two generic objects (T - T) in C# (Example: DateTime - DateTime)?

This is not possible with generics in C# - at least not directly. It has been a highly requested feature on Connect for a long time.

You will need to make your types implement some interface that has a member that can be used, and constrain the class to that, or use one of the workarounds listed in the Connect bug (none of which are perfect), or a separate approach like MiscUtil's generic operators.


Try something like this:

static void Main(string[] args)
{
    Tuple<int, bool> value = JustAMethod<int>(5, 3);
    if (value.Item2)
    {
        Console.WriteLine(value.Item1);
    }
    else
    {
        Console.WriteLine("Can't substract.");
    }
}
public static Tuple<T, bool> JustAMethod<T>(T arg1, T arg2)
{
    dynamic dArg1 = (dynamic)arg1;
    dynamic dArg2 = (dynamic)arg2;
    dynamic ret;
    try
    {
        ret = dArg1 - dArg2;
        return new Tuple<T, bool>(ret, true);
    }
    catch
    {
        return new Tuple<T, bool>(default(T), false);
    }
}

How this works: first, you convert the arguments to a dynamic type, and you can easily use operators on the dynamic type. If you wouldn't be able to use the operators, then an exception would be thrown at runtime. So, if you try to substract two objects that you actually can't substract, we'll catch the exception and return false as the second item in the Tuple.


this work

public object Duration
{
    get
    {
        return (dynamic)End - (dynamic)Start;
    }
}

but no check, and slow