Checking whether an object is Null before using it and throwing a Null Reference Exception if it is indeed Null, is a pretty repetitive task. Seeing code like this is not unusual:
private readonly List<string> people;
private readonly List<string> tasks;
public Without(List<string> people, List<string> tasks)
{
// Null Checking
if (people == null)
{
throw new NullReferenceException("people is Null");
}
if (tasks == null)
{
throw new NullReferenceException("tasks is Null");
}
// Field Initialisation
this.people = people;
this.tasks = tasks;
// Actual code we care about here.
}
This kinda get’s my aesthetic coding back up, it’s repetitive, wordy and defocuses our code from the job of doing something useful. Enter a generic extension method to take away the pain:
public static T ThrowIfNull<T>(this T value, string variableName) where T : class
{
if (value == null)
{
throw new NullReferenceException(string.Format("Value is Null: {0}", variableName));
}
return value;
}
Now we can refactor our original code to the following:
private List<string> people;
private List<string> tasks;
public With(List<string> people, List<string> tasks)
{
// Field Initialisation
this.people = people.ThrowIfNull("people");
this.tasks = tasks.ThrowIfNull("tasks");
// Actual code we care about here.
}
What’s more, because our extension method ultimately returns the object upon which it’s being enacted, we can chain methods to make even more succinct code:
private void AlternativeUse(List<string> places)
{
places.ThrowIfNull("places").Add("Home");
}
Happy coding.