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!