How can an object not be compared to null?

前端 未结 5 555
一整个雨季
一整个雨季 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 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? pair)
    {
        if (pair != null)
        {
        }
        // Other code
    }
    

    Note the ? in KeyValuePair?

提交回复
热议问题