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:
{
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) :
So in order to avoid this our check should be:
{
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, :
{
countryName = videoGame.Author.Country.Name;
}
Here’s the extension method:
{
public static TSource GetDefault<TSource>(this TSource source) where TSource : class
{
TSource sourceInstance = null;
sourceInstance = source ?? Activator.CreateInstance<TSource>();
return sourceInstance;
}
}
No Comments
You can leave the first : )