Consider this simple c# example:
var person = new Person {Name = "Fred", MailingAddress=null };
var result = String.Format("{0} lives at {1}",person.Name, person.MailingAddress.Street);
clearly this will throw a NullReferenceException because the MailingAddress proptery is null.
I could rewrite the second line as:
var result = String.Format("{0} lives at {1}", person.Name, person.MailingAddress == null ? (String)null : person.MailingAddress.Street);
Is there a simpler way to say express this?
There’s not really any good syntax for this. The coalesce operator is part of it, but you need to handle traversing through a null, not just replacing a null. One thing you could do would be to have a static “null object” for the class, something like:
Then you could use the coalesce operator like so:
If you want to go the extension method route, you could do something like this:
Then you could do: