Null Checking Made Easy

It’s fairly common for developers to need to move data from one class structure to another. If the class is complex you may find yourself writing endless null checks to ensure you don’t cause a NullReferenceException:

public PersonSummary CreateSummary(Person person)
{
    var summary = new PersonSummary();
    summary.Name = person.Name;

    if (person.Job != null)
    {
        summary.JobId = person.Job.Id;
        summary.StartDate = person.Job.StartDate;
    }

    if (person.Address != null)
    {
        summary.Street = person.Address.Street;
        summary.Town = person.Address.Town;
    }
    return summary;
}

This article includes a helper function that wraps this null check up so you can perform it in-line:

public PersonSummary CreateSummary(Person person)
{
    return new PersonSummary
    {
        Name = person.Name,
        JobId = GetValueOrDefault(person.Job, x => x.Id),
        StartDate = GetValueOrDefault(person.Job, x => x.StartDate),
        Street = GetValueOrDefault(person.Address, x => x.Street),
        Town = GetValueOrDefault(person.Address, x => x.Town)
    };
}

Here’s a simplified version of the function that just handles strings:

private static string GetString<T>(T model, Func<T, string> selector)
{
    if (model == null)
        return null;
    else
        return selector(model);
}

Here’s a more advanced generic version that handles any type:

private static TResult GetValueOrDefault<T, TResult>(T model, Func<T, TResult> selector)
{
    if (model == null)
        return default(TResult);
    else
        return selector(model);
}

For completeness, here’s the classes from the example:

public class Person
{
    public string Name { get; set; }
    public Job Job { get; set; }
    public Address Address { get; set;  }
}

public class Job
{
    public int Id { get; set; }
    public DateTime StartDate { get; set; }
}

public class Address
{
    public string Street { get; set; }
    public string Town { get; set; }
}

public class PersonSummary
{
    public string Name { get; set; }
    public int JobId { get; set; }
    public DateTime StartDate { get; set; }
    public string Street { get; set; }
    public string Town { get; set; }
}
Advertisements
This entry was posted in Tips and Tricks and tagged . Bookmark the permalink.

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