Search code examples
c#c#-6.0null-conditional-operator

Why does the null-conditional operator behave differently for == and .Equals()?


I had the following code, which works fine:

var firstChild = token.First as JProperty;
bool isHref = token.Children().Count() == 1
           && firstChild?.Name == "href";

I wanted to make the string comparison case-insensitive, so I changed it to:

var firstChild = token.First as JProperty;

bool isHref = token.Children().Count() == 1
           && firstChild?.Name.Equals("href", StringComparison.OrdinalIgnoreCase);

Now the compiler is giving me an error:

Operator && cannot be applied to operands of type 'bool' and 'bool?'

I can fix the error by coalescing to false like

bool isHref = token.Children().Count() == 1
         && (firstChild?.Name.Equals("href", StringComparison.OrdinalIgnoreCase) ?? false);

But I'm curious why the compiler doesn't like the first null-conditional syntax.


Solution

  • Let's simplify to the essentials.

    string x = null, y = null;
    
    // this is null.  b1 is bool?
    var b1 = x?.Equals(y); 
    
    // b2 is bool
    // this is true, since the operator doesn't require non-null operands
    var b2 = x == y;
    

    Basically .Equals() requires a non-null object to operate on. That's different than ==, which is statically bound, not dynamically dispatched.