Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 733
Dee J. Doena Avatar asked Jun 29 '16 15:06

Dee J. Doena


People also ask

How do you use the null operator?

The null coalescing operator is used with the nullable value types and reference types. It is used for converting an operand to the type of another nullable (or not) value type operand, where an implicit conversion is possible.

What is null conditional?

The null-conditional operators are short-circuiting. That is, if one operation in a chain of conditional member or element access operations returns null , the rest of the chain doesn't execute.

Which operator is used with null operator?

The ?? operator is used to check null values and you can also assign a default value to a variable whose value is null(or nullable type).

What is null conditional and null coalescing?

In cases where a statement could return null, the null-coalescing operator can be used to ensure a reasonable value gets returned. This code returns the name of an item or the default name if the item is null. As you can see, this operator is a handy tool when working with the null-conditional operator.


2 Answers

  • 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.
like image 86
Heinzi Avatar answered Oct 10 '22 17:10

Heinzi


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) 
like image 24
René Vogt Avatar answered Oct 10 '22 18:10

René Vogt