Handling Error - Object Reference Not Set To An Instance Of Object

Object Reference Not Set To An Instance Of Object is one of the most common errors. Here is the reason and solution of the Object Reference Not Set To An Instance Of Object error.

"Object reference not set to an instance of an object"

 
This is one of the most common errors when developing an application. In this article, I will be presenting five of the most common mistakes that result with this error and will explain how to avoid them. 
 
Why does this error happen?
 
This error's description speaks for itself but when you do not have much experience in development, it is very difficult to understand. So, this error description says that an object that is being called to get or set its value has no reference. This means that you are trying to access an object that was not instantiated.
 
Why should I know this?
 
This is important in order to avoid runtime errors that could possibly expose your sensitive data and this could lead to a vulnerability breach. Vulnerability breaches are usually used by hackers for a cyber attack to steal your data or to take your server offline.
 

How to avoid exposing code and entities?

 
You must always wrap code that could possibly throw an exception inside try-catch blocks. There are others security approaches that you can use to protect your data that can be found here.
 
Common mistakes
 
Objects used in this sample.
 
Controller
  1. public class HomeController : Controller  
  2.    {  
  3.        SampleObj sampleObj;  
  4.        SampleChildObj sampleChild;  
  5.        List<string> lstSample;  
  6.        public IActionResult Index()  
  7.        {  
  8.            return View();  
  9.        }  
  10.   
  11.        public IActionResult About()  
  12.        {  
  13.            ViewData["Message"] = "Your application description page.";  
  14.   
  15.            return View();  
  16.        }  
  17.   
  18.        public IActionResult Contact()  
  19.        {  
  20.            ViewData["Message"] = "Your contact page.";  
  21.   
  22.            return View();  
  23.        }  
  24.   
  25.        public IActionResult Error()  
  26.        {  
  27.            return View();  
  28.        }  
  29.        public IActionResult NewObject()  
  30.        {  
  31.            sampleChild.Item2 = "error";  
  32.            return View();  
  33.        }  
  34.   
  35.        public IActionResult ConditionStatement()  
  36.        {  
  37.            if (true == false)  
  38.            {  
  39.                sampleChild = new SampleChildObj();  
  40.                sampleChild.Item2 = "";  
  41.            }  
  42.            else  
  43.                sampleChild.Item2 = "error";  
  44.   
  45.            return View();  
  46.        }  
  47.        public IActionResult ObjectInsideObject()  
  48.        {  
  49.            sampleObj = new SampleObj();  
  50.            sampleObj.ChildObj.Item2 = "error";  
  51.            return View();  
  52.        }  
  53.        public IActionResult AddInNullList()  
  54.        {  
  55.            lstSample.Add("error");  
  56.            return View();  
  57.        }  
  58.    }  
Classes
  1. public class SampleObj  
  2. {  
  3.   
  4.     public string Item1 { getset; }  
  5.     public SampleChildObj ChildObj { getset; }  
  6. }  
  7. public class SampleChildObj   
  8. {  
  9.     public string Item2 { getset; }  
  10. }  

New object not instantiated

Practical example:
 
Here, we have a sample situation of when we have this error.
  1. public IActionResult NewObject()  
  2. {  
  3.     sampleChild.Item2 = "error";  
  4.     return View();  
  5. }  

This happens when you create a new object but do not instantiate it before getting/setting a value.

Condition statement(if, switch)

 
Practical example:
 
Here, we have a sample situation of when we have this error,
  1. public IActionResult ConditionStatement()  
  2. {  
  3.     if (true == false)  
  4.     {  
  5.         sampleChild = new SampleChildObj();  
  6.         sampleChild.Item2 = "";  
  7.     }  
  8.     else  
  9.         sampleChild.Item2 = "error";  
  10.   
  11.     return View();  
  12. }  

Why does this happen?

This is a very common mistake. It happens when you create an object that is going to be instantiated inside a conditional statement but forgets to instantiate it in one of the conditions and try to read/write on it.
 

Object Inside Object

 
Practical Example

Here, we have a sample situation of when we have this error:

  1. public IActionResult ObjectInsideObject()  
  2. {  
  3.     sampleObj = new SampleObj();  
  4.     sampleObj.ChildObj.Item2 = "error";  
  5.     return View();  
  6. }  

Why this happens?

It happens when you have an object with many child objects. So, you instantiate the main object but forget to instantiate its child before trying to get/set its value.
 

Add item in a null list

 
Practical Example
 
Here we have a sample situation of when we have this error,
  1. public IActionResult AddInNullList()  
  2. {  
  3.     lstSample.Add("error");  
  4.     return View();  

Why does this happen?

When you are trying to read/write data in a list that was not instantiated before.
 
Important
  1. In order to avoid exposing your data, you must always handle exceptions. Read more about how to do that here
  2. The items listed above are some of the most common ways to throw this type of error but there are many other situations in which we may face it. Always remember to check if your objects are instantiated before reading or writing data into them.

Best practices

  • Tips about commenting your code, making it more readable in order to help others developers to understand it.
  • Object naming practices, creating a pattern to name variables, services, methods.
  • Handling errors to not show sensitive data to your users.
  • Security tricks to protect your data.
  • Reading/writing data without breaking your architecture.

*I am planning to write more about common mistakes and to share tips to improve code quality. If you have any specific topic that you would like to read here, please write it below in the comments section.

Congratulations! You just learned how to deal with the most common daily mistakes.
 
Download the code from GitHub here.