Get to the Bottom of C# Object Reference Not Set to an Instance of an Object in Visual Studio

"Object reference not set to an instance of an object" error is one of the most common errors when developing .NET applications. Here are the five most common mistakes that result in this error. In this article, also learn how to fix errors, and object references not set to an instance of an object.

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  

public class HomeController : Controller  
{  
    SampleObj sampleObj;  
    SampleChildObj sampleChild;  
    List<string> lstSample;  
    public IActionResult Index()  
    {  
        return View();  
    }  

    public IActionResult About()  
    {  
        ViewData["Message"] = "Your application description page.";  

        return View();  
    }  

    public IActionResult Contact()  
    {  
        ViewData["Message"] = "Your contact page.";  

        return View();  
    }  

    public IActionResult Error()  
    {  
        return View();  
    }  
    public IActionResult NewObject()  
    {  
        sampleChild.Item2 = "error";  
        return View();  
    }  

    public IActionResult ConditionStatement()  
    {  
        if (true == false)  
        {  
            sampleChild = new SampleChildObj();  
            sampleChild.Item2 = "";  
        }  
        else  
            sampleChild.Item2 = "error";  

        return View();  
    }  
    public IActionResult ObjectInsideObject()  
    {  
        sampleObj = new SampleObj();  
        sampleObj.ChildObj.Item2 = "error";  
        return View();  
    }  
    public IActionResult AddInNullList()  
    {  
        lstSample.Add("error");  
        return View();  
    }  
}

Classes

public class SampleObj  
{
    public string Item1 { get; set; }  
    public SampleChildObj ChildObj { get; set; }  
}  
public class SampleChildObj   
{  
    public string Item2 { get; set; }  
}

New object not instantiated

Practical example,

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

public IActionResult NewObject()  
{  
    sampleChild.Item2 = "error";  
    return View();  
}

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,

public IActionResult ConditionStatement()  
{  
    if (true == false)  
    {  
        sampleChild = new SampleChildObj();  
        sampleChild.Item2 = "";  
    }  
    else  
        sampleChild.Item2 = "error";  
  
    return View();  
}

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:

public IActionResult ObjectInsideObject()  
{  
    sampleObj = new SampleObj();  
    sampleObj.ChildObj.Item2 = "error";  
    return View();  
} 

Why Does 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 an item in a null list

Practical Example

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

public IActionResult AddInNullList()  
{  
    lstSample.Add("error");  
    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, create a pattern to name variables, services, and 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 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.


Similar Articles