Ads by ProfitSence
Close

What does "Object reference not set to an instance of an object" mean?

Last Updated on Wednesday 5th Oct 2022

object reference not set to an instance of an object

Variables in .NET are either reference types or value types. Value types are primitives like integers and booleans or structures. boolean variables, when declared, have a default value.

			
					bool mybool;
//mybool == false

			
	

Reference types, when declared, have no default

			
					class ExampleClass
{

}

ExampleClass exampleClass; //== null

			
	
  • If you try to access a member of an instance of a class using a null reference, you will get a System.NullReferenceException.

  • This is the same as a reference to an object not set to an instance of an object .

			
					static void Main(string[] args)
{
    var exampleClass = new ExampleClass();
    var returnedClass = exampleClass.ExampleMethod();
    returnedClass.AnotherExampleMethod(); //NullReferenceException here.
}

class ExampleClass
{
    public ReturnedClass ExampleMethod()
    {
        return null;
    }
}

class ReturnedClass
{
    public void AnotherExampleMethod()
    {
    }
}

			
	
  • All of the above is really just hints at the basics of .NET type.

  • Also check out a much more complex example of when you might encounter a NullReferenceException.

  • You are trying to access an object without creating it.

  • You may need to use the "new" keyword to instantiate it first, that is, instantiate it.

			
					public class MyClass
{
   public int Id {get; set;}
}

MyClass myClass;

myClass.Id = 0; <----------- An error will be thrown here.. because myClass is null here...

			
	

You will have to use

			
					myClass = new MyClass();
myClass.Id = 0;