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 string if (list?.Count > 0) compiles fine, which means that if list is null , the expression Count > 0 defaults to false .

However, the if (a?.B) throws a compiler error saying that I cannot implicitly convert bool? in bool .

Why is one different from the other?

+59
c # nullable roslyn null-conditional-operator
Jun 29 '16 at 15:27
source share
2 answers
  • list?.Count > 0 : Here you are comparing int? with int , giving bool , since the removed comparison operators return a bool , not a bool? .
  • a?.B : Do you have a bool? . if , however, requires bool .
+69
Jun 29 '16 at 15:31
source share

In your first case ( list?.Count ) the operator returns int? - a value with a null int value.
The > operator is defined for integers with a zero value, so what if int? it does not matter (equal to null), the comparison will return false .

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

You can change this statement to:

 if (a?.B ?? false) 

so that he works again. Thus, the null-coalescing ( ?? ) operator returns false when the operator with the null condition ( ?. ) Returned null .

Or (as suggested by TheLethalCoder):

 if (a?.B == true) 
+37
Jun 29 '16 at 15:31
source share



All Articles