How can an object not be compared to null?

Viewed 22371

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?

5 Answers

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>?

Because KeyValuePair is structure (a value type), you can only compare nulls on reference types.

I'm guessing you haven't written that extra overload yet. It will fail when you attempt to pass null as the value of a KeyValuePair.

KeyValuePair<K,V> is a struct and hence can't be null under any circumstances. Only a reference type can be null.

If you're trying to catch an incorrect value you'll have to validate the Key and Value members individually.

Related