Dear Jon!
Thank you for your reply! It was very useful! A resulting question; what is
meant by "mutable" value types? From the context of your reply I suppose it
means that value type variables such as int and struct are inherently
mutable, i.e. can be assigned to an object variable? (Also known as boxing,
no?) Am I right, or are there also "non-mutable" value types?
Regards Carl Johansson
"Jon Skeet [C# MVP]" <sk***@pobox.comskrev i meddelandet
news:11*********************@q75g2000hsh.googlegro ups.com...
On Jun 20, 10:06 am, "Håkan Johansson"
<carl.johans...@nogarbagehallde.comwrote:
error CS0445: Cannot modify the result of an unboxing conversion
I'm quite new to C# and can't really see how to get rid of the above
error.
I have an ArrayList instance to which I add two types of elements. The
first
type of element is a class, the other type of element is a struct.
Sometimes
I need to change the field values of the elements held by the ArrayList.
In
the case of the class type element, this is no problem. However, in the
case
of the struct type element, C# won't allow it. First of all, I don't
really
understand why. Secondly, do I really have to create a new class with
similar content of the struct to get rid of this error?
Firstly, having a mutable struct is generally a bad idea - it's likely
to bite you sooner or later. This is an example of that.
When you fetch the element from the ArrayList and unbox it, the value
you've got back is now completely independent of the value in the
ArrayList - it's just a copy. If you change the value of a field
within that copy, it won't do what you want. So, you tend to need to
do things like this:
MyStruct x = (MyStruct) arrayList[5];
x.SomeProperty = 20;
arrayList[5] = x;
Now this problem doesn't apply to an array because array elements
effectively count as variables.
All of this is avoided by banning mutable value types. You still need
to change the value in the ArrayList manually, but you don't get into
diffculties working out the different situations and whether
something's made a copy or not.
Jon