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?

3

2 Answers 2

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");
}
Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

I suspect that a better implementation would be public List<string> Words { get; } = new List<string>(); (so someone can't come along and set Words to null).
I agree, I will add also this. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.