3

Why this c# code throws a null exception?

bool boolResult = SomeClass?.NullableProperty.ItsOkProperty ?? false;

Isn´t elvis operator supposed to stop evaluation (short circuit) once the NullableProperty evaluates to null?

In my understanding the line of code above is a shortcut for:

bool boolResult 
if(SomeClass != null)
    if(SomeClass.NullableProperty != null)
        boolResult = SomeClass.NullableProperty.ItsOkProperty;
    else
        boolResult = false;
else
    boolResult = false;

Did I assume wrong?

EDIT: Now I understand why I get it wrong, The line of code actually translates to something similar to:

bool boolResult 
if(SomeClass != null)
    boolResult = SomeClass.NullableProperty.ItsOkProperty;
else
    boolResult = false;

And throws because NullableProperty is null...

Paulo Morgado
  • 14,111
  • 3
  • 31
  • 59
Marcelo de Aguiar
  • 1,432
  • 12
  • 31
  • Ah, I think what you wanted was `SomeClass?.NullableProperty?.ItsOkProperty` –  Jun 10 '15 at 19:08

1 Answers1

9

You need to chain, since the NRE is on the second reference:

bool boolResult = SomeClass?.NullableProperty?.ItsOkProperty ?? false;
Mark Brackett
  • 84,552
  • 17
  • 108
  • 152