Get tips to solve null reference exception

What is NullReferenceException? Object reference not set to an instance of an object

Matt Watson Developer Tips, Tricks & Resources Leave a Comment

Null reference errors are responsible for a good percentage of all application bugs. They are usually very simple problems caused by not adding additional logic to ensure that objects have valid values before using them.  Here are some ways to avoid NullReferenceException.

The following code will throw a NullReferenceException if the variable “text” being passed in is null. You can’t call ToUpper() on a null string.

public void MyMethod(string text)
{
     //Throws exception if text == null
     if (text.ToUpper() == "Hello World")
     {
          //do something
     }
}

You can also have null reference exceptions because any type of object is null. For example, in the code below, the SqlCommand object is never initialized. Not running a SQL query would be a serious problem for your application. A null string might be something you just ignore and move on. Other times, like with the SqlCommand, it could be a fatal issue you don’t want to ignore.

SqlCommand command = null;
//Exception! Object reference not set to an instance of an object
command.ExecuteNonQuery();

Use the Null Conditional Operator to Avoid NullReferenceExceptions

One of the best new additions to C# was the null conditional operator. Instead of having a crazy amount of “variable != null” type checks, you can use the “?” and your code will short circuit and return null instead of throwing the exception. This will make more sense with some examples below:


Free Download

text?.ToUpper(); //from previous example, would return null

int? length = customerList?.Length; // null if customerList is null   
Customer first = customerList?[0];  // null if customerList is null  
int? count = customerList?[0]?.Orders?.Count();  // null if customerList, the first customer, or Orders is null  

Use Null Coalescing to Avoid NullReferenceExceptions

Another great feature is null coalescing, which is the “??” operator. It works great for providing a default value for a variable that is null. It works with all nullable datatypes.

The following code throws an exception without the null coalescing. Adding “?? new List<string>()” prevents the “Object reference not set to an instance of an object” exception.

List<string> values = null;

foreach (var value in values ?? new List<string>())
{
    Console.WriteLine(value);
}  

Simple Examples of Null Values Causing Problems

Some of the most common causes are settings, database calls, or API type calls not returning expected values. For example, you add a new field to your database and don’t populate default values for every record. Randomly records get queried, and the code didn’t account for that new field being null. KA-BOOM: Object reference not set to an instance of an object.

The Golden Rule of Programming

For years I have had a saying that I say to my team all the time. I call it the golden rule of programming.  I think every new programmer needs a tattoo that says it.

“If it can be null, it will be null”

The good news is that a lot of null reference errors can be avoided by adding additional logic and code to ensure objects are not null before trying to use them. Developers should always assume that everything is invalid and be very defensive in their code. Pretend every database call is going to fail, every field is going to have messed up data in it. Good exception handling best practices are critical.

Tips to Prevent Null Reference Exceptions

  1. Initialize variables with valid values.
  2. If a variable can be null, then check for null and handle it appropriately
  3. Use the ? operator on methods when possible. stringvar?.ToUpper();
  4. Use tools like Resharper to help point out potential null reference exceptions

Conclusion

Null reference exceptions are a very common problem in .NET and most programming languages. Luckily, we can all blame Tony Hoare. He invented null references and even calls it the billion dollar mistake.

If you follow my golden rule, I promise you will have far fewer bugs in your apps.  If it can be null, it will be null!

About Matt Watson

Matt is the Founder & CEO of Stackify. He has been a developer/hacker for over 15 years and loves solving hard problems with code. While working in IT management he realized how much of his time was wasted trying to put out production fires without the right tools. He founded Stackify in 2012 to create an easy to use set of tools for developers.