What is NullReferenceException?

DZone 's Guide to

What is NullReferenceException?

NullReferenceExceptions are object references not set to an instance of an object. Learn how they cause problems, and how to avoid them with your code.

· DevOps Zone ·
Free Resource

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.

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.

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:

text?.ToUpper(); //from previous example, would return null command?.ExecuteNonQuery(); //from previous example, would return null and not run a SQL command 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 > ()) {

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 NullReferenceExceptions

  1. Initialize variables with valid values.
  2. If a variable can be null, 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.

Null reference exceptions are a very common problem in .NET and all 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!

devops ,testing ,software development

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}