1

I want to write an instrumental generic function

    public static T F<T>(T a, T b) 
    {
        return a + b;
    }

But, it need the parameter has operators like +, -, etc. How do I implement this?

yymmyb
  • 84
  • 6

1 Answers1

1

This is not possible without a bit of tricking, because, as you may have notices, there's no way you can make the compiler know that instances of the unknown type T can be added. The following works, though:

public static T F<T>(T a, T b) 
{
    dynamic a1 = a;
    dynamic a2 = b;
    return a1 + b1;
}

It has a few issues, though: Since the operation is compiled at runtime, it may be slower than a default add, and it will compile, no matter what T is. Only if at runtime T has no operator+, it will throw an exception.

PMF
  • 14,535
  • 3
  • 23
  • 49