0

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?

Axel_s
  • 21
  • 4
  • https://docs.unity3d.com/Manual/JSONSerialization.html – Uzair Oct 05 '20 at 11:37
  • 2
    words is null. You have to initialize it by calling the constructor. `something.words = new List();` – Sebastián Oct 05 '20 at 11:38
  • 1
    Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – SomeBody Oct 05 '20 at 11:52

2 Answers2

1

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.

Christos
  • 53,228
  • 8
  • 76
  • 108
1
  1. Initialize words list in the constructor of the class, to make sure that it will exist.
public YourClass {
    words = new List<string>;
}
  1. Add new item to that list in the corresponding method.
public void YourMethod {
    words.Add("New Item");
}
kosist
  • 2,868
  • 2
  • 17
  • 30