Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a handy syntax to return null rather than exception when accessing a property of a null object

Tags:

syntax

c#

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?

like image 443
Ralph Shillington Avatar asked Feb 22 '23 07:02

Ralph Shillington


2 Answers

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; }
}
like image 146
Adam Rackis Avatar answered Mar 05 '23 17:03

Adam Rackis


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)
like image 26
Bryn Keller Avatar answered Mar 05 '23 15:03

Bryn Keller