Skip to content

Object Reference Not Set To An Instance Of Object

Most of the C# programmers get to see this error once a while:

Object Reference Not Set To An Instance Of Object

In this article we will see why this error occurs, and how we can fix it.

Cause of the issue

This error message is self explanatory, but for new developer, this error message says that object doesn’t have any instance. Simply it means the object used is not initialised and code is trying to access it’s fields like property, variables or methods.

Fix for this Issue

There could be many ways this issue could exist in your code. I will list some that you need to keep track of and try to prevent below.

Best way to handle this issue is to always use try catch block, and if you getting the object as result of any function call then make sure you always check it for null.

try {
    var myObject = Anotherunction();
    // this can cause error
    myObject.SayHello();

    // Correct way to prevent this issue
    if(myObject != null){
        myObject.SayHello();
    }
}
catch {
// you logic to handle error
}

Make Sure You Initialise the Object

Visual Studio is very good in tracking if the object is initialised or not, if not, then it will show green jiggly lines under the variable name, and in case its not declared then during compiling it will throw error. But in case you are using any other code editor like Visual Studio Code, then it will not warn us that object is not initialised.

try {
    // New object is created, but it is not initialized
    Person myObject;

    // long lines of other codes
    // .......
    // .......
    // .......
    // .......


    // this will give error, as object is not initialized
    myObject.GetFullName();
}
catch {
// you logic to handle error
}

Mostly we get this issue because we get the object as a result of another function call, and we don’t know weather that object is null or not, and without checking its nullability we try to access its field. So always make sure you check for null in these scenarios.

Happy coding!!

Be First to Comment

Leave a Reply

Your email address will not be published.