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.
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 thec.dados[0]
?– edro
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 theList
not be ideal for you, depending on what you want to do.– Kevin Kouketsu