How can an object not be compared to null?

前端 未结 5 538
一整个雨季
一整个雨季 2020-12-06 09:07

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, wh

相关标签:
5条回答
  • 2020-12-06 09:30

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

    0 讨论(0)
  • 2020-12-06 09:34

    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

    0 讨论(0)
  • 2020-12-06 09:39

    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.

    0 讨论(0)
  • 2020-12-06 09:40

    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.

    0 讨论(0)
  • 2020-12-06 09:43

    You can actually use KeyValuePair.IsNull() to determine if the KeyValuePair has been set.

    0 讨论(0)
提交回复
热议问题