EDUDOTNET

Saturday, August 3, 2013

Exception: "Object reference not set to an instance of an object”

What do you mean by "Object reference not set to an instance of an object”?

Approximate every day, C# programmers getting this type of error and ask:
Why do I get the error "Object reference not set to an instance of an object"?
The program is trying to access a member of a reference type variable which is set to null that is a main reason getting type of exceptions.
In the Main method, notice that edudotnet is set to null. Therefore, the following code will throw a NullReferenceException:
Since edudotnet is null, it has no members to be accessed. Whereas the preceding example used a roperty call, the following example source code uses a method call:

The preceding code will throw a NullReferenceException; because, edudotnet is still null. It is irrelevant that the first example call was a property and the second was a method: they are both members of the type.  
To solve this edudotnet, be sure the edudotnet object is instantiated before being referenced.The following samplesource code instantiates edudotnet and, so, avoids the error message:Now, edudotnet contains a reference to an instance of EDUDOTNET; so, any of its members can be called.

2 comments: