List and array of values ​​structs vs variable

I'm trying to understand / reconcile my understanding of how C # structures work when chaining using List and Arrays. I follow Eric's explanation in this post Performance of an array of structure types

but I take this step further.

struct Foo { public int A; public int B; public Foo[] ChildFoos; } Foo parentFoo = new Foo(); parentFoo.ChildFoos = new Foo[1]; parentFoo.ChildFoos[0] = new Foo(); List<Foo> list = new List<Foo>(); list.Add(parentFoo); 

But behavior changes when you connect challenges. list [0] should return a value (not a variable) when ChildFoos [0] should return a variable.

 list[0].ChildFoos[0].A = 4545; 

In this case, it appears that list [0] is considered as a variable instead of a value. ChildFoos [0] .A supports the new value in parentFoo in the list. How is this possible?

Compare this to trying to set A to the parent structure of Foo, which will not compile.

 list[0].A = 877; 

This will not compile

+5
source share
1 answer

So, as you rightly said, list[0] is a copy of the value in the list. This value is not a variable. One of the meanings in this struct is ChildFoos . The value of this field is not a series of instances of Foo; instead, it is a reference to a bunch of information stored elsewhere (since arrays are reference types). The copy of the Foo instance you got back has a copy of the link that the instance has inside the list.

If you had to change the link itself, say by assigning a new ChildFoos array, you will see the same error that you see when you try to change any other field of this structure, for example, when you try to mutate A Since you only read the value of the link that the struct stores (and does not mutate an instance of the structure), then it goes over and gets the first element in this array, and since the index index of the array returns a variable, not a value (again, as you correctly noted in the question ), mutating, which returned the instance of Foo , mutates the instance in the array, since it is not a copy, so when you access the same array again, you can observe the change later.

+2
source

Source: https://habr.com/ru/post/1273927/


All Articles