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?
This code is technically a violation of the Law of Demeter, so some would consider it bad form to write this in the first place.
So no, there's no native syntax to accomplish what you want, but moving this code to a property in your Person
class would make this calling code more clean, and also bring you in line with the law of demeter.
public string StreetAddress{
get { return this.MailingAddress == null ?
(String)null : person.MailingAddress.Street; }
}
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:
public class Address
{
public static Address Null = new Address();
// Rest of the class goes here
}
Then you could use the coalesce operator like so:
(person.MailingAddress ?? Address.Null).Street
If you want to go the extension method route, you could do something like this:
public static class NullExtension
{
public static T OrNew<T>(this T thing)
where T: class, new()
{
return thing ?? new T();
}
}
Then you could do:
(person.MailingAddress.OrNew().Street)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With