I want to be able to call properties on objects that might be null but not explicitly have to check whether they are null or not when calling.
Like this:
var something = someObjectThatMightBeNull.Property;
My idea is to create a method that takes an Expression, something like this:
var something = GetValueSafe(() => someObjectThatMightBeNull.Property);
TResult? GetValueSafe<TResult>(Expression<Func<TResult>> expression)
where TResult : struct
{
// what must I do?
}
What I need to do is to inspect the expression and determine if someObjectThatMightBeNull is null or not. How would I do this?
If there is any smarter way of being lazy I’d appreciate that too.
Thanks!
It’s complicated, but it can be done, without leaving “expression-land”:
That being said, as Andras Zoltan has so eloquently put in the comments: “Just because you can doesn’t mean you should.” Make sure you have a good reason to do this. If there’s a better way to, then do that instead. Andras has a great workaround.