Home >Backend Development >C++ >Why are My List Items Overwriting Each Other in C#?
C# list object value is overwritten: reference semantic issue
Why do all items in the list overwrite the previous values when adding a new value to the list? This puzzling behavior stems from the underlying data structures and reference semantics in C#.
Understand the semantics of classes and structures
In C#, classes are reference types, which means that variables of class type store a reference to the actual object location in memory. On the other hand, structures are value types, and variables directly hold the actual data.
In the code snippet provided:
<code class="language-csharp">List<Tag> tags = new List<Tag>(); Tag _tag = new Tag(); string[] tagList = new[] { "Foo", "Bar" }; foreach (string t in tagList) { _tag.tagName = t; // 设置所有属性 tags.Add(_tag); // 覆盖之前的数值 }</code>
Since _tag
is a reference type, the tags.Add(_tag)
operation adds a reference to the same object to the list. As a result, all elements in the list actually point to the same instance. Modifying an instance via _tag
will change all items in the list.
Resolve the problem by creating a new instance
To prevent overwriting, a new Tag
instance should be created for each iteration of the loop:
<code class="language-csharp">foreach (string t in tagList) { Tag _tag = new Tag(); // 为每次迭代创建一个新实例 _tag.tagName = t; tags.Add(_tag); }</code>
Now, each iteration creates a new Tag
instance, ensuring that each object in the list has its own unique value.
Additional Note: Structures and Classes
Using structs instead of classes eliminates overwriting issues because structs are value types. When a structure is assigned to a new variable, it creates a completely new instance containing its own set of values. Therefore, tags.Add(_tag)
performs a copy operation and does not affect previously added items.
In summary, understanding reference semantics and the difference between classes and structs is crucial to avoid overwriting issues in lists of objects in C#.
The above is the detailed content of Why are My List Items Overwriting Each Other in C#?. For more information, please follow other related articles on the PHP Chinese website!