Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I wrote a Generic Class:

public class Interval<T> where T : IComparable // for checking that Start < End 
{
    public T Start { get; set; }
    public T End { get; set; }
    ...
}

And I use this class with DateTime, int, etc.

I need a Duration property that returns a duration like:

public object Duration
{
    get
    {
        return End - Start;
    }
}

But when this property is included in my class, the compiler raises a logical error on the - operator.

What can I do to achieve this goal normally, or should I ignore it?

like image 658
Reza ArabQaeni Avatar asked Nov 18 '11 20:11

Reza ArabQaeni


1 Answers

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.

like image 118
ProgramFOX Avatar answered Oct 11 '22 04:10

ProgramFOX