Note: This question was asked before the introduction of the .?
operator in C# 6 / Visual Studio 2015.
We've all been there, we have some deep property like cake.frosting.berries.loader that we need to check if it's null so there's no exception. The way to do is is to use a short-circuiting if statement
if (cake != null && cake.frosting != null && cake.frosting.berries != null) ...
This is not exactly elegant, and there should perhaps be an easier way to check the entire chain and see if it comes up against a null variable/property.
Is it possible using some extension method or would it be a language feature, or is it just a bad idea?
Where you need to achieve this, do this:
Usage
or
Helper class implementation
I've found this extension to be quite useful for deep nesting scenarios.
It's an idea I derrived from the null coalescing operator in C# and T-SQL. The nice thing is that the return type is always the return type of the inner property.
That way you can do this:
...or a slight variation of the above:
It's not the best syntax I know, but it does work.
I like approach taken by Objective-C:
"The Objective-C language takes another approach to this problem and does not invoke methods on nil but instead returns nil for all such invocations."
Besides violating the Law of Demeter, as Mehrdad Afshari has already pointed out, it seems to me you need "deep null checking" for decision logic.
This is most often the case when you want to replace empty objects with default values. In this case you should consider implementing the Null Object Pattern. It acts as a stand-in for a real object, providing default values and "non-action" methods.
There is Maybe codeplex project that Implements Maybe or IfNotNull using lambdas for deep expressions in C#
Example of use:
The link was suggested in a similar question How to check for nulls in a deep lambda expression?
Try this code: