I have some code that is extracting a value at the end of a long property chain where any one of the properties could be null.
For example:
var value = prop1.prop2.prop3.prop4;
In order to handle the possibility of null in prop1 I have to write:
var value = prop1 == null ? null : prop1.prop2.prop3.prop4;
In order to handle the possibility of null in prop1 and prop2 I have to write:
var value = prop1 == null
? null
: prop1.prop2 == null ? null : prop1.prop2.prop3.prop4;
or
var value = prop1 != null && prop1.prop2 != null
? prop1.prop2.prop3.prop4
: null;
If I want to handle the possibility of null in prop1, prop2 and prop3 as well, or even longer property chains, then the code starts getting pretty crazy.
There must be a better way to do this.
How can I handle property chains so that when a null is encountered, null is returned?
Something like the ?? operator would be great.
Update
As of C# 6, a solution is now baked into the language with the null-conditional operator;
?.for properties and?[n]for indexers.Old Answer
I had a look at the different solutions out there. Some of them used chaining multiple extension method calls together which I didn’t like because it wasn’t very readable due to the amount of noise added for each chain.
I decided to use a solution that involved just a single extension method call because it is much more readable. I haven’t tested for performance, but in my case readability is more important than performance.
I created the following class, based loosely on this solution
This allows me to write the following:
xwill contain the value ofscholarshipApplication.Scholarship.CostScholarship.OfficialCurrentWorldRankingornullif any of the properties in the chains return null along the way.