Reputation: 21
I'm trying to add a string to an object in c# like this: The class is:
class thing
{
public int somenumber { get; set; }
public int someothernumber { get; set; }
public List<string> words { get; set; }
}
I'm trying to do
var something = new thing();
something.words.Add("some word");
How do I add a string to the list 'words' without getting nullreference-errors?
Upvotes: 0
Views: 107
Reputation: 53958
You have first to create a list, since by default words
would be null.
var something = new thing();
something.words = new List<string>();
Then you can use the newly created list, as you have already done:
something.words.Add("some word");
Now when something.words
would point to the newly created list and it wouldn't be null.
Another more consistent way to do this, is to create that list in the class constructor:
public class Thing
{
public int SomeNumber { get; set; }
public int SomeOtherNumber { get; set; }
public List<string> Words { get; set; }
public Thing()
{
Words = new List<string>();
}
}
btw, please also look at the naming conventions (e.g. properties name start with capital letters as well as class names).
Update
As correctly matthew-watson mentioned in his comments, there is also another way (probably better) for doing the same thing:
public class Thing
{
public int SomeNumber { get; set; }
public int SomeOtherNumber { get; set; }
public List<string> Words { get; } = new List<string>();
}
Doing so, we create a read-only list. Essentially when we create an instance of this class a new list of strings is created and it's reference is assigned to the Words backing field. From that moment, you can't change the reference that is stored in that backing field and you can use the list only for adding/removing things, you can't change it's reference.
Upvotes: 1
Reputation: 3077
words
list in the constructor of the class, to make sure that it will exist.public YourClass {
words = new List<string>;
}
public void YourMethod {
words.Add("New Item");
}
Upvotes: 1