Adding items to a List<T>
in C# can sometimes lead to unexpected results: all items end up identical to the last one added. This article explains why and how to fix it.
Let's examine a simplified scenario:
<code class="language-csharp">List<Tag> tags = new List<Tag>(); Tag _tag = new Tag(); // Problem: Single instance reused string[] tagList = new[] { "Foo", "Bar" }; foreach (string t in tagList) { _tag.tagName = t; tags.Add(_tag); }</code>
The issue stems from reusing the same _tag
instance within the loop. Each iteration modifies the same object, resulting in all list entries holding the final value.
The Solution: New Instances for Each Item
The correct approach is to create a fresh _tag
object for every loop iteration:
<code class="language-csharp">foreach (string t in tagList) { Tag _tag = new Tag(); // New instance each time _tag.tagName = t; tags.Add(_tag); }</code>
This ensures each list element is a distinct object, preserving unique values.
Bonus: The Behavior of Structs
Interestingly, if Tag
were a struct instead of a class, the original code would work correctly. This difference arises from how classes and structs handle memory allocation.
Classes are reference types; passing a class by value only copies the reference, not the object itself. Modifying the parameter within a method alters the original object. Structs, however, are value types. Passing a struct by value creates a copy. Therefore, adding _tag
(a struct) to the list adds a copy, preventing overwrites.
The above is the detailed content of Why Does Adding Items to a List Result in Overwriting?. For more information, please follow other related articles on the PHP Chinese website!