Object reference not set to an instance of an object
An Object is an instance of a Class , it is stored some where in memory. A reference is what is used to describe the pointer to the memory location where the Object resides. The message "object reference not set to an instance of an object" means that you are referring to an object the does not exist or was deleted or cleaned up. This would usually be a run-time error .
Variables in .NET are either reference types or value types . Value types are primitives such as integer and boolean or structure. For ex. Boolean variables, when declared, have a default value:
Reference types, when declared, do not have a default value:
If you try to access a member of a class (here MyClass) then you get a System.NullReferenceException. Which is the same as "object reference not set to an instance of an object" . It indicates that you are trying to access member fields, or function types, on an object reference that points to null. That means the reference to an Object which is not initialized. However, the null-reference exception is designed as a valid runtime condition that can be thrown and caught in normal program flow.
It's usually better to avoid a NullReferenceException than to handle it after it occurs. To prevent the error, objects that could be null should be tested for null before being used.
Object Reference variable is just like "pointer in C" but not exactly a pointer. A NullReferenceException typically reflects developer error and is thrown in the following scenarios:
- Forgotten to instantiate a reference type.
- Forgotten to dimension an array before initializing it.
- Is thrown by a method that is passed null.
- Get a null return value from a method, then call a method on the returned type.
- Using an expression to retrieve a value and, although checking whether the value is null.
- Enumerating the elements of an array that contains reference types, and attempt to process one of the elements.
Handling an exception can make your code harder to maintain and understand, and can sometimes introduce other bugs. However, there are many situations where handling the error can be useful:
- Your application can ignore objects that are null.
- You can restore the state of your application to a valid state.
- You want to report the exception.