Among my list of commonly occur error one of the most disturbing error for new coders is “object reference not set to an instance of an object” .

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

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. string var?.ToUpper();
  4. Use tools like Resharper to help point out potential null reference exceptions