C# .NET Generics – How Can an Object Not Be Compared to Null?

.netc++generics

I have an 'optional' parameter on a method that is a KeyValuePair. I wanted an overload that passes null to the core method for this parameter, but in the core method, when I want to check if the KeyValuePair is null, I get the following error:

Operator '!=' cannot be applied to operands of type System.Collections.Generic.KeyValuePair<string,object>' and '<null>. 

How can I not be allowed to check if an object is null?

Best Answer

KeyValuePair<K,V> is a struct, not a class. It's like doing:

int i = 10;
if (i != null) ...

(Although that is actually legal, with a warning, due to odd nullable conversion rules. The important bit is that the if condition will never be true.)

To make it "optional", you can use the nullable form:

static void Foo(KeyValuePair<object,string>? pair)
{
    if (pair != null)
    {
    }
    // Other code
}

Note the ? in KeyValuePair<object,string>?