Home >Backend Development >C++ >Why Are My List Items Overwritten When Adding Multiple Objects?
Issue:
Adding multiple items to a list results in all list items being overwritten with the value of the last added item. This happens regardless of the items' initial values.
Causes:
Resolution:
The solution involves creating a new object instance for each iteration:
<code class="language-csharp">foreach (string t in tagList) { Tag _tag = new Tag(); // New Tag object for each iteration _tag.tagName = t; tags.Add(_tag); }</code>
Alternative: Utilizing Structs
Switching from a class to a struct eliminates the overwrite problem because:
Add
operation creates a new struct instance, maintaining unique values.The above is the detailed content of Why Are My List Items Overwritten When Adding Multiple Objects?. For more information, please follow other related articles on the PHP Chinese website!