A
A
Andrey At2016-03-18 02:35:34
C++ / C#
Andrey At, 2016-03-18 02:35:34

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
}

As far as I understand, due to the fact that the structure is not a reference type, but a value type, then if the structure element is in the list, then the Change () function does not change its value, but something else. Can you please explain where is the problem here? What exactly changes the value in the Change() function?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stanislav Silin, 2016-03-18
@Atomov

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 question

Ask a Question

731 491 924 answers to any question