Compare an instance of param type to null, even without class constraint?


The following code compiles:

class Testing<TKey, TValue>
    public bool Test(TKey key)
        return key == null;

However, TKey can be a value type, and possibly not allow the value "null".

I know the results of this program, and how to add constraints. What I'm wondering is why doesn't the compiler disallow this when TKey is not constrained to "class"?

It's convenient to be able to do this in various cases. If TKey is a non-nullable value type, the result of the comparison will always be false. (It's possible that the JITter will remove that branch entirely - don't forget that although one version of the JITted code is shared for all reference types, it reJITs for each value type.)

EDIT: One interesting use for this is precisely to allow Nullable<T> comparisons with null. TFoo=Nullable<T> doesn't satisfy either the where TFoo : class or where TFoo : struct constraints.