Default value if null object in an extension method.

Sometimes you need to get a value from a nested object and in order to do it we need to be sure that the object hierarchy do not have any null objects in it.

This lead to a long series of checks. Here an example, assuming we got these entities:

Code Snippet
  public class Country
  {
      public string Name { get; set; }
  }

  public class Author
  {
      public string Name { get; set; }
      public DateTime DateOfBirth { get; set; }
      public Country Country { get; set; }
  }

  public class Character : BaseEntity
  {
      public int Name { get; set; }
      public bool IsEvil { get; set; }
      public virtual ICollection<Videogame> Videogames { get; set; }
  }

  public class Videogame : BaseEntity
  {
      public string Name { get; set; }
      public DateTime ReleasedDate { get; set; }
      public virtual ICollection<Character> Characters { get; set; }
      public Author Author { get; set; }
  }

When trying to get the contry name of the author of a videogame, we should check both the Author and the Country object not to be null otherwise we’ll get the following (where Author is null) :

image

So in order to avoid this our check should be:

Code Snippet
if (videoGame.Author != null && videoGame.Author.Country != null)
{
    countryName = videoGame.Author.Country.Name;
}

But this can become really verbose if there’s a lot of nesting in place. Let’s then use an extension method that allow to get a default value for each object in the chain that is null, :

Code Snippet
if (videoGame.Author.GetDefault().Country != null)
{
    countryName = videoGame.Author.Country.Name;
}

Here’s the extension method:

Code Snippet
public static class DefaultIfNullExtension
{
    
    public static TSource GetDefault<TSource>(this TSource source) where TSource : class
    {
        TSource sourceInstance = null;
        sourceInstance = source ?? Activator.CreateInstance<TSource>();
        return sourceInstance;
    }

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s