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
newkeyword.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 theNullReferenceException.Consider two classes;
PersonandFullName. ThePersonclass contains an instance of aFullNameclass.
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
Personinstance is instantiated, theFullNameinstance within is not.A proper way of handling this situation is as follows.
Last updated