Trying to understand ?. (null-conditional) operator in C#

倖福魔咒の 提交于 2019-12-04 14:55:48

问题


I have this very simple example:

class Program
{
    class A
    {
        public bool B;
    }

    static void Main()
    {
        System.Collections.ArrayList list = null;

        if (list?.Count > 0)
        {
            System.Console.WriteLine("Contains elements");
        }

        A a = null;

        if (a?.B)
        {
            System.Console.WriteLine("Is initialized");
        }
    }
}

The line if (list?.Count > 0) compiles perfectly which means that if list is null, the expression Count > 0 becomes false by default.

However, the line if (a?.B) throws a compiler error saying I can't implicitly convert bool? to bool.

Why is one different from the other?


回答1:


  • list?.Count > 0: Here you compare an int? to an int, yielding a bool, since lifted comparison operators return a bool, not a bool?.
  • a?.B: Here, you have a bool?. if, however, requires a bool.



回答2:


In your first case (list?.Count) the operator returns an int? - a nullable int.
The > operator is defined for nullable integers so that if the int? has no value (is null), the comparison will return false.

In your second example (a?.B) a bool? is returned (because if a is null, neither true nor false but null is returned). And bool? cannot be used in an if statement as the if statement requires a (non-nullable) bool.

You can change that statement to:

if (a?.B ?? false)

to make it work again. So the null-coalescing operator (??) returns false when the null-conditional operator (?.) returned null.

Or (as TheLethalCoder suggested):

if (a?.B == true)


来源:https://stackoverflow.com/questions/38103963/trying-to-understand-null-conditional-operator-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!