I bet you have ! You just need to get the value of xx.Foo.Bar.Baz.Name, but you have to test every intermediate object to ensure that it’s not null. It can quickly become annoying if the property you need is nested in a deep object graph….

A solution

Linq offers a very interesting feature which can help solve that problem : expressions. C# 3.0 makes it possible to retrieve the abstract syntax tree (AST) of a lambda expression, and perform all kinds of manipulations on it. It is also possible to dynamically generate an AST, compile it to obtain a delegate, and execute it.

How is this related to the problem described above ? Well, Linq makes it possible to analyse the AST for the expression that accesses the xx.Foo.Bar.Baz.Name property, and rewrite that AST to insert null checks where needed. So we’re going to create a NullSafeEval extension method, which takes as a parameter the lambda expression defining how to access a property, and the default value to return if a null object is encountered along the way.

That method will transform the expression xx.Foo.Bar.Baz.Name into that :

Indexers are not handled yet, but they could be added quite easily ; I will leave it to you to do it if you have the use for it 😉

Limitations

Even though that solution can seem very interesting at first sight, please read what follows before you integrate this code into a real world program…

First, the proposed code is just a proof of concept, and as such, hasn’t been thoroughly tested, so it’s probably not very reliable.

Secondly, keep in mind that dynamic code generation from an expression tree is tough work for the CLR, and will have a big impact on performance. A quick test shows that using the NullSafeEval method is about 10000 times slower than accessing the property directly…

A possible approach to limit that issue would be to cache the delegates generated for each expression, to avoid regenerating them every time. Unfortunately, as far as I know there is no simple and reliable way to compare two Linq expressions, which makes it much harder to implement such a cache.

Last, you might have noticed that intermediate properties and methods are evaluated several times ; not only this is bad for performance, but more importantly, it could have side effects that are hard to predict, depending on how the properties and methods are implemented.

A possible workaround would be to rewrite the conditional expression as follows :

Unfortunately, this is not possible in .NET 3.5 : that version only supports simple expressions, so it’s not possible to declare variables, assign values to them, or write several distinct instructions. However, in .NET 4.0, support for Linq expressions has been largely improved, and makes it possible to generate that kind of code. I’m currently trying to improve the NullSafeEval method to take advantage of the new .NET 4.0 features, but it turns out to be much more difficult than I had anticipated… If I manage to work it out, I’ll let you know and post the code !

To conclude, I wouldn’t recommend using that technique in real programs, at least not in its current state. However, it gives an interesting insight on the possibilities offered by Linq expressions. If you’re new to this, you should know that Linq expressions are used (among other things) :

To generate SQL queries in ORMs like Linq to SQL or Entity Framework

To build complex predicates dynamically, like in the PredicateBuilder class by Joseph Albahari

– .NET 4 Contracts come to mind instantly. They were made for issues like this.
– If you check the objects very often and use a default instead – use the Null Object pattern http://en.wikipedia.org/wiki/Null_Object_pattern
– For collections never put null in but an empty collection

I often ask myself whether people really just want quiet software (xx.Foo.Bar.Baz.Property should always not raise an error) instead of sensible software (cc.Foo.Bar.Baz.Property raises an error when Bar is null because Bar could/should never be null).
If you want default values you got to have an “else” case anyway. The Null Object pattern was made to give you a good default case.

We have a “solution” like yours by a different programmer in one of my projects. He was not able to answer me WHY and WHEN Bar or Baz could be null and WHY it should not raise an error if this happens even he didn”t know why it should happen. He also regularly used default(T) in cases where null appeared instead of reporting it. Yes, we got EMPTY textboxes (string.Empty) instead of null exceptions. I would have preferred the exception as we didn”t have empty strings in the db, only NULL values…

@RickRock, as I mentioned in my article, this “solution” is only a proof of concept, it”s not a recommendation of something you should do of course…
I agree that you should throw if an object happens to be null when it”s not expected, but in some cases you know it can be null, and it can be a valid state; in those cases you have to properly handle the case where it”s null, not throw an exception.