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

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?

This question is related to c# asp.net nullreferenceexception

The answer is


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.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to nullreferenceexception

How to solve Object reference not set to an instance of an object.? Value cannot be null. Parameter name: source Error checking for NULL in VBScript Checking session if empty or not Checking if an object is null in C# What is a NullReferenceException, and how do I fix it? C# elegant way to check if a property's property is null What does "Object reference not set to an instance of an object" mean?