Search code examples
c#lambdaexpression-trees

Check for Null in an Expression


I have an Expression that looks like this:

obj => obj.Child.Name

where Name is a string. What I want to do is get the value of Name. I can get it just fine by compiling the method and invoking it, however a NullReferenceException is thrown if Child is null. Is there a way to check if Child is null in this scenario?


Solution

  • With the current C# version 5.0 (or lower), you have to explicitly check for each property like:

    if(obj != null && obj.Child != null)
    {
      //get Name property
    }
    

    With C# 6.0 you will be able to check it using Null conditional/propagation operator.

    Console.WriteLine(obj?.Child?.Name);