direct access to struct variables in List<struct> compiler error ?

B

Bill Woodruff

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
 
J

Jon Skeet [C# MVP]

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.

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.
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.

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.
I wonder if this is yet another of the interesting differences in having a
constructor-less struct vs. having a struct with a constructor ?

Sort of.

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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top