Click here to Skip to main content
15,891,783 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,

I have many time found on my system that error comes as
"Object reference not set to an instance of an object".

I know it says that null value taken.

But i want to know what is exact solution for that.
It comes many times i resolved some time but i actully could not get thoroughly.
Posted

Hi,

The error
Quote:
"Object reference not set to an instance of an object"
will come with the following reasons.

1.) If you have an object or a variab;le which is declared but not initialized as mentioned in the above solution.

2.) If your object that is returning from any of the method or service is not having any values and you are trying to retrieve some values there then also you will get such error.

3.) Lets say you have refered a config value from any file location and the file is not available then also you will receieve such error message.

Hope from all these examples you can able to clear why you are having such errors.

To solve this kind of errors you need to have the null check in your code and you should return some meaningful error message to the returning function and display that in the UI.

Thanks
Sisir Patro
 
Share this answer
 
scenario1. all explained above comments
scenario2:this, comes in code behind also, if u without creating controls in aspx page, but trying to assign value to also,the same error will come.
 
Share this answer
 
You need to initialize the object.
It happens when you do not use the keyword "new"

Example You have a class "Car" and you want to use it somewhere in the code.

C#
public Class Car{
  public Color CarColor{ set; get; }
  public int TopSpeed { set; get; }
  public string Make { set; get; }
  public string Model { set; get; } 
}


Causing the exception like this:
C#
Car car;
car.TopSpeed = 250;  //nullreference exception here


Avoiding the excpetion like this:
C#
//to avoid nullreference exception
Car car = new Car();
car.TopSpeed = 250;  //no error thrown the topspeed property is set to 250.


using the "new" keyword will make the program, reserve memory, as it where, for all the variables/functions that that class needs. In this case the application will reserve memory to hold CarColor, TopSpeed, Make and Model.

If you want another car, make sure to use the "new" keyword again:
C#
Car car2 = new Car();


otherwise you get the exception again.

Hope this helps.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900