Check for Null in an Expression

113 views Asked by At

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?

4

There are 4 answers

0
Habib On BEST ANSWER

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);
1
maraaaaaaaa On
obj => obj.Child == null ? "" : obj.Child.Name;
0
Fixation On
obj => obj.Child == null ? null : obj.Child.Name

or using C# 6

obj => obj.Child?.Name
0
Miguel Ruiz On

You can filter them previously(with a Where), something like this:

var results = source.Where(obj => obj.Child != null).Select(obj => obj.Child.Name);

Like this, you will prevent those null reference errors.