Saturday, April 16, 2011

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

Before refer any method or property in an instance of class, make sure the instance is not null


class Class1
{
    public void AnotherExampleMethod()
    {
    }
}
static void Main(string[] args)
{
    var exampleClass = new Class1();    exampleClass.AnotherExampleMethod(); //OK

    var exampleClass1 = null;
exampleClass1.AnotherExampleMethod(); //
//NullReferenceException here. Object reference not set to an instance of an object
}

No comments:

Post a Comment