.NET Framework - direct access to struct variables in List<struct> compiler error ?

Asked By Bill Woodruff on 24-Feb-08 12:12 AM
Hi,

Assume you have a simple struct defined in its own file

namespace testStruct
{
public struct myStruct
{
public string data1;
public string data2;
}
}

You manufacture instances of myStruct in your application and store them in
a Generic List of form :

public List<myStruct> myStructList;

If you attempt in code to do something like this (assuming there is at least
two myStructs stored in the List) :

myStructList[1].data2 = "changed data";

You'll get a compiler error saying : "Cannot modify the return value of
System.Collections.List<testStruct.myStruct> this[int] because it is not a
variable.

However you can do this with no problem at compile or run-time :

myStruct scratchStruct = myStructList[1];
scratchStruct.data2 = "changed data";

I am baffled by why you can't directly assign to public variables inside an
instance of a public struct. My usual resources (Liberty, Sells, Petzold,
Archer, Gunnerson) don't yield any information on this.

I wonder if this is yet another of the interesting differences in having a
constructor-less struct vs. having a struct with a constructor ?

thanks, Bill Woodruff




Jon Skeet [C# MVP] replied on 24-Feb-08 02:25 AM
And that's a good thing. It's preventing a bug - because if this were
allowed, it wouldn't do what you think it does.


When you use myStructList[1] that's calling a property, which is
returning a value.

When you use scratchStruct, that's a variable.

You can't assign a value to a struct's variable via a value expression,
only via a variable.

Even in the code which compiles, you're not changing what's in the list
at all though.


Sort of.

It's definitely another example of why mutable value types are a bad
idea.

--
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet   Blog: http://www.msmvps.com/jon.skeet
World class .NET training in the UK: http://iterativetraining.co.uk