With C# 6 we can use the new ?
to access properties and methods without heaving to check each one for null. Would it be possible to write a method that has a siliar functionality using expressions?
For example I have to use a weird object structures (that comes from a 3rd party library that we cannot change). Accessing some properties requires often long chains of dots:
rootObject.Services.First().Segments.First().AnotherCollection.First().Weight;
Any of the objects after rootObject
can be null
. I would rather not put a try/catch
around it. Also checking each property separately is a lot of work. So I was wondering if I could pass it to the method taking an expression and traverse each property and check its value there:
var value = PropertyHelper.GetValue(() => rootObject.Services.First().Segments.First().AnotherCollection.First().Weight);
I guess its signature would be something like:
public static T GetValue<T>(Expression<Func<T>> expression)
{
// analyze the expression and evaluate each property/method
// stop when null or return the value
}
I'm not realy sure if expressions are capable of what I'm going to do and before I start experimenting I wanted to ask whether it's even possible.