Ivan said:
where MyType is a struct, attempt to modify an item with
items[0].member = something;
Cannot modify the return value of
'System.Collections.Generic.List<MyType>.this[int]' because it is not a
variable (CS1612) - E:\project\MainForm.cs:189,8
While searching the documentation I haven't found a specific mention
that it *should* work, but it seems logical. How to get around the
restriction?
How wise of the compiler to prevent you from doing that. If it would
have let you, you would have changed the member of the copy of the value
that you requested from the list. This would have no effect at all, as
the original value in the list would be unchanged.
If you want to change the member of a struct, you have to get a copy of
the value, change the member, and replace the original value with the
changed value:
MyType temp = items[0];
temp.member = something;
items[0] = temp;
However, a struct should generally be immutable. If you have items that
you want to modify, you should make it a class instead.
Sorry, probably slightly off topic, but I don't consider that the best
advice. Certainly you should think long and hard before creating a
mutable struct, precisely because of the behaviour the OP just
observed: they act in ways that aren't intuitive to the casual C#
programmer.
I would be more inclined to say the following: "If you have items that
logically should be structs, but you want to be able to modify them,
then realize that allowing structs to be modified in place is just
syntactic sugar for adding another constructor. Consider doing that
instead."
Viz:
structValue.Member = newValue;
is equivalent to:
structValue = new MyStruct(structValue, newValue);
A bit more typing, perhaps, and a few more bytes get moved around, but
nothing earthshaking.
Some examples of mutable structs in the .NET Framework (which cause no
end of consternation if this newsgroup is anything to go by) are Point
and Rectangle. The posts asking why you can't do this:
myForm.Location.X = 5;
seem to have died down lately, but I'm waiting for them to flare up
again.
Anyway, I don't consider it a good idea to decide between using struct
and class based on whether you think the thing should be mutable. IMHO
it has much more to do with semantics, in particular what I refer to
as "whether the thing has an identity."