Add value to a string list

Asked

Viewed 262 times

1

I have a class, and in it I have a List<string> and I just create it to add the values elsewhere. But when I try to add a value, I get the following error:

Nullreferenceexception: Object Reference not set to an instance of an Object.

I’ll make a clearer example of how I’m doing:

Class with the list:

public class cl{
    public List<string> dados { get; set; }
}

Adding value to the list:

public IActionResult OnPost(cl c){
    c.dados.Add("teste");
}

From there I get the mistake I left above.

I’m using the . Net Core Razor.

2 answers

4


You need to create an instance of your List.
You can do it like this:

public List<string> dados { get; set; } = new List<string>();

The above code creates an instance of List of strings, Thus, its object will be accessible, that is, properly instantiated and ready for use. And your problem will be solved.

Classes in C# are not automatically initialized. Therefore, you always need to initialize them in some way other than structs, for example, that are não-nuláveis by default.

If his List will only be initialized within this classe and not change, you can by her as just get:

public List<string> dados { get; } = new List<string>();
  • Good Kevin. But what about in case I want to value a certain line on that list? For example c.dados[0] = "bb", when I try to do this, it still gives error. I need to make a .Add() first to use the c.dados[0]?

  • Yes, the list starts empty, that is, Dice 0 does not exist yet, there is no way to access it. If you want to access an index directly, the ideal is to check the size before, with .Length. Maybe the List not be ideal for you, depending on what you want to do.

4

Note that in your class cl you say there is a list of strings called dados but you did not start it. When creating this class, this list exists but is null until you instantiate it.

Before your line c.dados.Add("teste"); just do: c.dados = new List<string>(); and this should solve your problem.

Another option would be to create a constructor for your class cl and in this constructor instantiate the list:

public class cl{
    public List<string> dados { get; set; }

    public cl() {
       dados = new List<string>();
   }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.