-3

When I run this code i get a Null Reference exception error when I try to add a tag to the tagCollection. I'm pretty it's an issue with how I've declared tagCollection but I'm not sure where I'm going wrong.

The 2 classes setup are to enable me serialize the collection back to a JSON file once I have finished collecting my data.

 class TagCollection
{
    [JsonProperty("tags")]
    public List<Tag> Tags { get; set; }
}

public class Tag
{
    [JsonProperty("name")]
    public string Name { get; set; }

    [JsonProperty("id")]
    public string Id { get; set; }

    [JsonProperty("value")]
    public string Value { get; set; }
}

private TagCollection tagCollection;  

private void createCollection(){

    tagCollection.Tags.Add(
        new Tag { Name = "Test", Id = "tag1", Value = "145" }
    );

}
Phill360
  • 27
  • 3
  • Reference types are not automatically instantiated in C#. `private TagCollection tagCollection` and `public List Tags { get; set; }` both reference _nothing_ until you assign a value to them (i.e.a new instance). See [this answer](https://stackoverflow.com/a/16597945/3181933) from the duplicate. – ProgrammingLlama Jun 19 '19 at 01:00

1 Answers1

2

Change this:

private TagCollection tagCollection;

for this:

private TagCollection tagCollection = new TagCollection();

You just forgot to call new on the collection.

Update: You also need to change the declaration of Tags (Credits to user @John):

public List<Tag> Tags { get; set; } = new List<Tag>();
ichramm
  • 6,437
  • 19
  • 30