Search code examples
c#stringc#-4.0null-coalescing-operatornull-coalescing

C# coalesce operator Throws


I have a class with a string property. I use the coalesce operator when reading from it as it might be null, but it still throws me an NullRefrenceExeption.

string name = user.Section.ParentSection.Name ?? string.Empty;

To be more specific, its the ".ParentSection" that's null so is it because it don't even have ".name" ? If that's the case should i test ".ParentSection" first with an if block?

I assume there are something about the Coalesce operator i dont understand, hope someone can shed some light on whats going wrong here.


Solution

  • To be more specific, its the ".ParentSection" that's null so is it because it don't even have ".name" ?

    Yes.

    If that's the case should i test ".ParentSection" first with an if block?

    Yes.