Handling 'null'

  • One of the most prevalent mistakes newcomers make when it comes to handling class objects is referencing uninitialized objects, which generates a NullReferenceException.

  • Consider the following, where a class instance is declared, but not instantiated using the new keyword.

    • In this case, the 2nd line of code will throw a NullReferenceException.

Person person = null;
person.Id = 1;
  • Classes may contain objects of other classes.

  • These can be referenced by the . operator, but if they were not instantiated before accessing, they'll throw the NullReferenceException.

  • Consider two classes; Person and FullName. The Person class contains an instance of a FullName class.

public class FullName
{
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public string FirstNameLastName { get { return FirstName + " " + LastName; } }
    public string LastNameFirstName { get { return LastName + ", " + FirstName; } }

    public FullName() { }

    public FullName(string firstName, string lastName)
    {
        FirstName = firstName;
        LastName = lastName;
    }
}

public class Person
{
    public int Id { get; set; }
    public FullName FullName { get; set; }
}
  • Now, if we were to write the following code, it would throw a NullReferenceException.

  • This is because, although the Person instance is instantiated, the FullName instance within is not.

  • A proper way of handling this situation is as follows.

Last updated