Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to solve Object reference not set to an instance of an object.? [duplicate]

In my asp.net program.I set one protected list.And i add a value in list.But it shows Object reference not set to an instance of an object error

protected List<string> list; protected void Page_Load(object sender, EventArgs e) {      list.Add("hai"); } 

How to solve this error?

like image 473
r.vengadesh Avatar asked Nov 22 '13 08:11

r.vengadesh


People also ask

How do you fix object reference not set to an instance of an object?

To fix "Object reference not set to an instance of an object," you should try running Microsoft Visual Studio as an administrator. You can also try resetting the user data associated with your account or updating Microsoft Visual Studio to the latest version.

How do I fix NullReferenceException in C#?

You can eliminate the exception by declaring the number of elements in the array before initializing it, as the following example does. For more information on declaring and initializing arrays, see Arrays and Arrays. You get a null return value from a method, and then call a method on the returned type.

What is the meaning of object reference not set to an instance of an object in C#?

The error means that your code is trying to access/reference an object that is a null valued object that is not there in memory.


2 Answers

You need to initialize the list first:

protected List<string> list = new List<string>(); 
like image 116
Tinsa Avatar answered Sep 19 '22 22:09

Tinsa


I think you just need;

List<string> list = new List<string>(); list.Add("hai"); 

There is a difference between

List<string> list;  

and

List<string> list = new List<string>(); 

When you didn't use new keyword in this case, your list didn't initialized. And when you try to add it hai, obviously you get an error.

like image 37
Soner Gönül Avatar answered Sep 20 '22 22:09

Soner Gönül