0

I have estimated a courious effect with null propagation as you can see here:

1. string x = "SomeString";    
2. Console.WriteLine(! x?.Equals(null) ?? (false) ? true : false);   // true
3. Console.WriteLine(! x?.Equals(null) ?? (true) ? false : true);    // false (!)
4. Console.WriteLine(! x?.Equals(null));                             // true 

Can someone explain why the expression in Line 3. evaluates to false? As I understand the null propagation operator ?? is only executed, if an expression is null, but as you can see in line 4. the expression to the left evaluates to true, and not to null.

So if !x?.Equals(null) is true, why the null propagation to the right ?? (true) ? false : true changes this value to false?

I'm sure the error is to me and my understanding, but I have broken this error down now for hours, and I am really confused. Thanks for any explanation to this.

Helmut
  • 426
  • 3
  • 14
  • 4
    I think you might be getting confused with operator precedence/associativity? The line in question works as `(!x?.Equals(null) ?? (true)) ? false : true` – UnholySheep Mar 17 '22 at 20:53
  • 2
    I know you spent some serious thinking to come up with the most useless title possible, but please for future questions just put information what you are asking in the title not just "is it a bug", "help me" text that can't help real users of the site (future visitors). – Alexei Levenkov Mar 17 '22 at 21:30
  • 1
    Note that `??` is not "null propagation" operator... (Shameless self-promotion - https://stackoverflow.com/questions/43075113/what-does-a-question-mark-mean-in-c-sharp-code) – Alexei Levenkov Mar 17 '22 at 21:34

1 Answers1

1

The expression on Line 4 is true.

Using that in L3: The null coalescing operator has no effect, as L4 is not null, which leaves you with:

L4 ? false : true

Which evaluates to false when L4 is true.

Ian
  • 303
  • 3
  • 5
  • Thank you very much, now it is very clear to me. I have already seen the explanation at https://stackoverflow.com/questions/511093/what-is-the-operator-precedence-of-c-sharp-null-coalescing-operator about operator precedence – Helmut Mar 18 '22 at 10:42