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?
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.
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.
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.
You need to initialize the list first:
protected List<string> list = new List<string>();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With