Home > Backend Development > C++ > Why Does Adding Multiple Objects to a List Overwrite Previous Entries?

Why Does Adding Multiple Objects to a List Overwrite Previous Entries?

Susan Sarandon
Release: 2025-01-19 20:18:17
Original
277 people have browsed it

Why Does Adding Multiple Objects to a List Overwrite Previous Entries?

Understanding List Overwrites When Adding Multiple Objects

Adding multiple objects to a list can lead to unexpected behavior: all list entries might end up with the same value as the last object added. This happens because of a shared reference to a single object instance.

Let's look at an example:

<code class="language-csharp">public class Tag
{
    public string TagName { get; set; }
}

List<Tag> tags = new List<Tag>();
Tag tag = new Tag(); // This is the problem!
string[] tagList = new[] { "Foo", "Bar" };

foreach (string t in tagList)
{
    tag.TagName = t; 
    tags.Add(tag); 
}</code>
Copy after login

The code creates one Tag object (tag) outside the loop. The loop then repeatedly modifies this same object and adds it to the list. Consequently, all list entries point to the same object, reflecting only the final TagName assignment.

The Solution: Create New Instances Within the Loop

To correct this, create a new Tag object inside the loop for each iteration:

<code class="language-csharp">foreach (string t in tagList)
{
    Tag tag = new Tag(); // Create a new instance each time
    tag.TagName = t;
    tags.Add(tag);
}</code>
Copy after login

This ensures each list entry references a unique Tag object with its own distinct TagName.

Alternative: Using Structs

Classes in C# are reference types. Structs, on the other hand, are value types. Using a struct can avoid the overwrite problem because a copy of the struct is created when added to the list.

<code class="language-csharp">public struct Tag
{
    public string TagName { get; set; }
}

List<Tag> tags = new List<Tag>();
foreach (string t in tagList)
{
    Tag tag = new Tag { TagName = t }; //Creates a new instance each time
    tags.Add(tag);
}</code>
Copy after login

This approach provides a concise and efficient solution by leveraging the inherent copy-on-assignment behavior of structs. However, note that structs should be used judiciously and only when appropriate for the data they represent.

The above is the detailed content of Why Does Adding Multiple Objects to a List Overwrite Previous Entries?. 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