Thursday, February 12, 2015

Method with C# Generic Cannot Have == (Equality) or Comparison Operator

Problem:

You have written a function like the following;

       static Boolean IsV1GtV2(T v1, T v2)
        {
            return v1 > v2;
        }

And you get a compiler error stating;

Operator '>' cannot be applied to operands of type 'T' and 'T'

The error is reasonable, since there is no gurantee that some generic type T would support comparison.

The Following will Also Break

So next you could have tried.

return (int) v1 > (int) v2;

And you still cannot get that to work. 

Solution

The only real way it works (for me at least) is to work the code this way. 

            if (typeof (T) == typeof (System.Int32))
            {
                return (int) (object) v1 > (int) (object) v2;
            }

You wold, of course, need to add this type of block for every possible type that you plan to use.







Post a Comment