IList <mutable_struct> vs mutable_struct []
Ok, letβs have the code:
//I complie nicely ValueType[] good = new ValueType[1]; good[0].Name = "Robin"; //I don't compile: Cannot modify expression because its not a variable IList<ValueType> bad = new ValueType[1]; bad[0].Name = "Jerome"; struct ValueType { public string Name; } What exactly happens behind the scenes, because of which the compiler does not work?
//Adding to watch the following good.GetType().Name //Value = "ValueType[]" It a ValueType array. bad.GetType().Name //Value = "ValueType[]" Also a ValueType array. The compiler stops me from changing the member of the copy of the object I want to change. But why is a copy created from this array?
A little more research is tossed:
var guess = (ValueType[]) bad; guess[0].Name="Delilah"; Now, what do you think bad[0].Name ? That's right, this is Delilah.
Why is the value type copied from
IList<ValueType>, but not from an array
Because the array is an inline construct known to the compiler. Its operator [] has built-in semantics that provide the compiler with a modifiable link inside the array itself.
When the compiler is dealing with an interface, on the other hand, all that knows is that it returns a copy of the type of value you are trying to change. In other words, the compiler treats the IList operator [] and the array operator [] differently.
Note: It goes without saying that this exercise has purely academic significance because volatile structures are evil .