Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can an object not be compared to null?

Tags:

c#

.net

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?

like image 989
ProfK Avatar asked Mar 15 '09 16:03

ProfK


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

like image 72
Jon Skeet Avatar answered Sep 22 '22 16:09

Jon Skeet


I'm answering this despite its age because it is the 1st Google result for "test keyvaluepair to null"

The answer specified is correct, but it doesn't completely answer the problem, at least the one I was having, where I need to test the existence of the KeyValuePair and move on to another check of the Dictionary if it doesn't exist the way I'm expecting.

Using the method above didn't work for me because the compiler chokes on getting KeyValuePair.Value of KeyValuePair<>?, so it is better to utilize default(KeyValuePair<>) as seen in this question + answers. The default for KeyValuePair

like image 25
eudaimos Avatar answered Sep 22 '22 16:09

eudaimos