Answer the question
In order to leave comments, you need to log in
What is the problem with accessing the fields of a structure inside a list?
Faced with unexpected for me behavior of structure in C#.
public struct MyStruct
{
public int x;
public MyStruct(int a)
{
x = a;
}
public void Change(int b)
{
x = b;
}
}
public void MyFunc()
{
List<MyStruct> myStructList = new List<MyStruct>();
myStructList.Add(new MyStruct(13));
// myStructList[0].x содержит значение 13
myStructList[0].Change(43);
// myStructList[0].x по прежнему содержит значение 13
}
Answer the question
In order to leave comments, you need to log in
When you get a structure from the list through an indexer, a copy of it is returned, so you call the method for it. Then it is destroyed, and the one in the list will remain unchanged.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question