Home > Backend Development > C++ > Why Does Adding Items to a List Result in Overwriting?

Why Does Adding Items to a List Result in Overwriting?

Susan Sarandon
Release: 2025-01-19 20:30:14
Original
695 people have browsed it

Why Does Adding Items to a List Result in Overwriting?

Understanding List Overwrites in C#

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template