-1

We are comparing complex objects and generating data based on expressions.

We pass an expression to a method and execute some logic in there.

Inside this code we compile the expression to get the value of it, but sometimes these expressions are throwing null reference exceptions, because the objects can be null. We wrote a quickfix by catching the exceptions, but this slows down the application dramatically and it is not a clean solution.

Now what I really would like to do is to check each member if it is null, or that the whole expression doesn't throw a null reference exception when we run compile.

This is how we call the method, and it's possible that User or Address is null.

Compare( () => someObjectA.User.Address.City, () => someObjectB.User.Address.City);

In the compare method we try to get the values of each of the objects and compare them.

void Compare<TField>( Expression<TField> left, Expression<TField> right) {

object lValue;
object rValue;

try{
lValue = left.Compile().Invoke();
} catch{
lValue = default;
}


try{
rValue = right.Compile().Invoke();
} catch{
rValue = default;
}

}

I want to remove these try catches and do some null check using the expression.

I tried some things, but I cannot get it to work properly. I was hoping anyone could point me in the good direction?

In advance I thank you for your time!

Michael
  • 31
  • 8
  • 1
    Why are you using lambdas and expressions instead of simply evaluating the properties? –  Jul 19 '19 at 15:55
  • Have you looked into using the null-conditional operator? It's pretty handy. https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/member-access-operators#null-conditional-operators--and- – Chris Jul 19 '19 at 15:55
  • 1
    How about the ?: operator –  Jul 19 '19 at 15:57
  • I simplified the example, so I understand it doesn't make sense why I want to use this, but it's used for a generic compare method. Cannot use the ?. operator for this. – Michael Jul 20 '19 at 19:40
  • @servy Thank you for the link to that question! Great help! – Michael Jul 22 '19 at 12:07

1 Answers1

-1

You can just use the null operator ?, if an object is null it will defer to the value after the double question mark ??.

Compare( () => someObjectA?.User?.Address?.City ?? [somevalue],
         () => someObjectB?.User?.Address?.City ?? [somevalue]);
Sean T
  • 2,414
  • 2
  • 17
  • 23
  • Thank you for you reply, but the ?. notation isn't an option here. – Michael Jul 20 '19 at 19:33
  • 1
    Why not? It would have helped if you specified this in your question no? – Sean T Jul 21 '19 at 11:03
  • Thank you for your feedback. That would have been helpful indeed. To answer your question. In an expression tree lambda may not contain a null propagating operator. – Michael Jul 22 '19 at 06:20