I have the following ugly code:
if (msg == null ||
msg.Content == null ||
msg.Content.AccountMarketMessage == null ||
msg.Content.AccountMarke
You can lazily evaluate the values using lambda expressions. This is overkill for a simple null check, but can be useful for chaining more complex expressions in a "fluent" manner.
// a type that has many descendents
var nested = new Nested();
// setup an evaluation chain
var isNull =
NullCheck.Check( () => nested )
.ThenCheck( () => nested.Child )
.ThenCheck( () => nested.Child.Child )
.ThenCheck( () => nested.Child.Child.Child )
.ThenCheck( () => nested.Child.Child.Child.Child );
// handle the results
Console.WriteLine( isNull.IsNull ? "null" : "not null" );
This is a full example (albeit draft-quality code) that can be pasted into a console app or LINQPad.
public class Nested
{
public Nested Child
{
get;
set;
}
}
public class NullCheck
{
public bool IsNull { get; private set; }
// continues the chain
public NullCheck ThenCheck( Func
Again: you probably shouldn't use this in lieu of simple null checks due to the complexity it introduces, but it's an interesting pattern.