System.NullReferenceException: Object reference not set to an instance of an object.
How to fix "NullReferenceException was unhandled; System.NullReferenceException: Object reference not set to an instance of an object." error in C#.net. What is this error and when does it occur? Some common issue scenarios and solutions to avoid them.
This is the most common error which programmers often run into. So what is this error and when does it occur?Consider the below code snippet:
class A
{
int[] indexValue;
void SomeMethod()
{
indexValue[0] = 1; //line no: 6
indexValue[1] = 2;
}
}
During compilation of the above code snippet compiler will throw null reference error at line number six. This happens because you are trying to access an object to which reference does not exist! So the next question is what is a reference and how to create one to fix the error?
In order to access an object's properties and methods residing in memory you need its address. That address is known as reference. Creating reference is very simple in C#.net. We use the new keyword to create reference to an object. How to use the 'new' keyword?
int[] indexValue = new int[2];
The new keyword creates an object and returns the reference of the created object. So now indexValue contains the reference to the newly created object using which we can perform various operations on the object.
One more thing to keep in mind, not all null reference errors are discovered during compilation. Some subtle errors come to light only during runtime.
Below is one such situation:
void MethodOne()
{
int[] index = new int[2];
index = null; //index not referencing any object
CloneArray(index);
}
void CloneArray(int[] sa)
{
object o = sa.Clone();//throws null reference error
}
To avoid such situations you must always check the parameter for null at the beginning of the method.
if(sa == null)
{
//Take some action
}
Hi
Declare
int []index = new int[5];
Thanks
umesh bhosale