C# – Understanding the Null-Conditional Operator

c#-6.0c++null-conditional-operatornullableroslyn

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?

Best Answer