Home >Backend Development >C++ >How Can I Modify Values Within a List of Structs in C#?

How Can I Modify Values Within a List of Structs in C#?

DDD
DDDOriginal
2025-01-02 17:28:391021browse

How Can I Modify Values Within a List of Structs in C#?

Changing Values in a List of Structs

When working with a list of structs, one may encounter an error when attempting to modify elements. This issue arises due to the value type semantics of structs, which create separate instances for each value type variable. As a result, when a struct element is copied into another variable, its modification does not affect the original element.

The solution to this dilemma lies in the fact that structs can expose interfaces. By creating an interface with a set accessor for the desired property, one can modify the underlying struct via the interface reference, which points to the boxed object. The following code demonstrates this concept:

public interface IMyStructModifier
{
    String Name { set; }
}

public struct MyStruct : IMyStructModifier
{
    ...
}

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

// Using a boxed object
MyStruct temp = (MyStruct)obList[1];
temp.Name = "Gishu";

// Using the interface
IMyStructModifier temp2 = obList[1] as IMyStructModifier;
temp2.Name = "Now Gishu";

This method allows for the modification of elements in a list of structs, although it may result in boxing. Therefore, when considering the design of a type, the need for collection storage and modification should not override the appropriate semantic choice between a class and a struct.

The above is the detailed content of How Can I Modify Values Within 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