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:(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:
Note the ? in
KeyValuePair<object,string>?