Home >Backend Development >C++ >How to Modify Elements in a List of Structs in C#?

How to Modify Elements in a List of Structs in C#?

Barbara Streisand
Barbara StreisandOriginal
2025-01-01 04:49:10384browse

How to Modify Elements in a List of Structs in C#?

Modifying Elements in Lists of Structs

Problem:

When attempting to modify an element in a list of structs using the array index operator (e.g., MyList[1].Name = "bob"), an error is encountered: "Cannot modify the return value of 'System.Collections.Generic.List.this[int]' because it is not a variable."

Explanation:

This error arises due to the value type semantics of structs. Structs are copied by value, meaning that when an element is accessed from a list of structs, a new instance is created and the values are copied. Therefore, modifying this new instance does not affect the original element in the list.

Solution:

Consider Using Classes Instead:

If the need to modify elements in a list is critical, consider using classes instead of structs. Classes are reference types, which means they are passed by reference rather than by value. Modifying an element in a list of classes will directly affect the original instance.

Expose an Interface:

Ifstructs are required, one solution is to expose an interface on the struct. This allows modifications to be made through the interface reference, which points to the boxed object.

public interface IMyStructModifier
{
    String Name { set; }
}

public struct MyStruct : IMyStructModifier ...

Example:

List<Object> obList = new List<object>();
obList.Add(new MyStruct("ABC"));
obList.Add(new MyStruct("DEF"));

IMyStructModifier temp = obList[1] as IMyStructModifier;
temp.Name = "Now Gishu";

foreach (MyStruct s in obList) // => "ABC", "Now Gishu"
{
    Console.WriteLine(s.Name);
}

The above is the detailed content of How to Modify Elements in a List of Structs in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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