Why does adding a new value to list<> overwrite previous values in the list<>
In the loop where you add the tags to the collection, you're using the same object instance of Tag. Essentially, you're setting a Tag's name to the first value in tagList and adding it to the collection, then you're changing that same Tag's name to the second value in tagList and adding it again to the collection.
Your collection of Tags contains several references to the same Tag object! Instantiate _tag inside the for loop each time before setting the Tag's name and adding it to the collection.
You're using the same instance of the Tag
object inside the loop, so each update to the TagName
is to the same reference. Move the declaration inside the loop to get a fresh object on each pass of the loop:
foreach (string t in tagList)
{
Tag _tag = new Tag(); // create new instance for every iteration
_tag.tagName = t;
tags.Add(_tag);
}
For bonus part - when you change Tag
from class
to struct
copy operation (that happens when you call tags.Add(_tag)
) copies whole instance (essentially creating new one) unlike in original class
case when only reference to the same single instance is copied into the parameter of the call and then to the list's element (see C# pass by value vs. pass by reference for explanation on how struct
passed to method calls).