473,569 Members | 2,555 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

List<> of struct with property. Cannot change value of property. why?

This returns the following error:
"Cannot modify the return value of
'System.Collect ions.Generic.Li st<MyStruct>.th is[int]' because it is
not a variable"
and I have no idea why! Do lists return copies of their elements?
Why can't I change the element itself?

class Program
{
private struct MyStruct
{
private int myVar;
public int MyProperty
{
get { return myVar; }
set { myVar = value; }
}
}

private static List<MyStructli st = new List<MyStruct>( );

private static void Main(string[] args)
{
MyStruct x = new MyStruct();
x.MyProperty = 45;
list.Add(x);
list[0].MyProperty = 45; // <----------- ERROR HERE
}
}

Zytan

May 14 '07 #1
45 18810
On May 14, 10:28 am, Zytan <zytanlith...@g mail.comwrote:
This returns the following error:
"Cannot modify the return value of
'System.Collect ions.Generic.Li st<MyStruct>.th is[int]' because it is
not a variable"
and I have no idea why! Do lists return copies of their elements?
Yes. The [] operator on a list is, in fact, a function, so the value
stored at that location in the list is returned as a function result,
on the stack.

This doesn't cause problems for reference types, because usually you
want to change some property of the reference type, so the fact that
you get a copy of the reference in the list (not the actual reference
that is in the list) doesn't cause problems.

However, for value types exactly the same thing happens, and it does
cause problems: the value is copied from the list onto the stack and
returned as a function result. Modifying the returned value, of
course, has no effect on the contents of the list. The compiler wisely
catches this.
Why can't I change the element itself?

class Program
{
private struct MyStruct
{
private int myVar;
public int MyProperty
{
get { return myVar; }
set { myVar = value; }
}
}

private static List<MyStructli st = new List<MyStruct>( );

private static void Main(string[] args)
{
MyStruct x = new MyStruct();
x.MyProperty = 45;
list.Add(x);
list[0].MyProperty = 45; // <----------- ERROR HERE
}
}
You need to do this:

MyStruct y = list[0];
y.MyProperty = 45;
list[0] = y;

May 14 '07 #2
Yes. The [] operator on a list is, in fact, a function, so the value
stored at that location in the list is returned as a function result,
on the stack.
Ok.
This doesn't cause problems for reference types, because usually you
want to change some property of the reference type, so the fact that
you get a copy of the reference in the list (not the actual reference
that is in the list) doesn't cause problems.
Right, so that's why it's normally not an issue.
However, for value types exactly the same thing happens, and it does
cause problems: the value is copied from the list onto the stack and
returned as a function result. Modifying the returned value, of
course, has no effect on the contents of the list. The compiler wisely
catches this.
Yup, and structs are value types, so this makes sense.
You need to do this:

MyStruct y = list[0];
y.MyProperty = 45;
list[0] = y;
Ok, thanks, Bruce!! This helps a lot!

Zytan

May 14 '07 #3
The compiler wisely
catches this.
NOTE, the compiler does NOT catch everything! The following code
escapes detection:

MyStruct x = new MyStruct();
list[index].MethodThatChan gesStructsField s(x);

I guess this could be shortened to:

list[index].MethodThatChan gesStructsField s();

And likely THAT escapes detection, as well. Damn! I've been changing
all my ararys that are created dynamically (length unknown) into
List<>, to avoid Array.Resize.

Zytan

May 14 '07 #4
I guess this could be shortened to:
>
list[index].MethodThatChan gesStructsField s();
Confirmed. This operates on the COPY, and any changes are lost, and
the compiler does NOT warn about this.

Zytan

May 14 '07 #5
On Mon, 14 May 2007 11:38:10 -0700, Zytan <zy**********@g mail.comwrote:
[...]
I guess this could be shortened to:

list[index].MethodThatChan gesStructsField s();

And likely THAT escapes detection, as well. Damn! I've been changing
all my ararys that are created dynamically (length unknown) into
List<>, to avoid Array.Resize.
Well, you can still apply the same technique Bruce mentions:

MyStruct x = list[index];

x.MethodThatCha ngesStructsFiel ds();
list[index] = x;

Pete
May 14 '07 #6
Zytan <zy**********@g mail.comwrote:
I guess this could be shortened to:

list[index].MethodThatChan gesStructsField s();

Confirmed. This operates on the COPY, and any changes are lost, and
the compiler does NOT warn about this.
No, and there's no way it could. There's nothing available to the
compiler to let it know that the method changes the contents of the
struct.

(Remember when we warned you about making mutable structs, back in
March? This is just one of the problems. Just say no to mutable
structs, basically :)

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
May 14 '07 #7

If you declare your structure to implement an interface and then
declare the list as containing the interface instead of the structure,
then you can work with the structure (through the interface
implemented members) directly (interfaces allow you to pierce the
box).

Code sample below.
HTH,

Sam
------------------------------------------------------------
We're hiring! B-Line Medical is seeking .NET
Developers for exciting positions in medical product
development in MD/DC. Work with a variety of technologies
in a relaxed team environment. See ads on Dice.com.
public static void Test()
{
MyClass[] classArray = new MyClass[1];
MyStruct[] structArray = new MyStruct[1];
MyInterface[] interfaceArray = new MyInterface[1];
List<MyClasscla ssList = new List<MyClass>(1 );
List<MyStructst ructList = new List<MyStruct>( 1);
List<MyInterfac einterfaceList = new List<MyInterfac e>(1);

classArray[0] = new MyClass();
classList.Add(n ew MyClass());
interfaceArray[0] = new MyStruct();
structList.Add( new MyStruct());
interfaceList.A dd(new MyStruct());

classArray[0].X++;
interfaceArray[0].X++;
structArray[0].X++;
classList[0].X++;

// Cannot modify the return value of 'List<MyStruct> .this[int]'
// because it is not a variable
//structList[0].X++;
interfaceList[0].X++;

Console.WriteLi ne("Class Array : " + classArray[0].X);
Console.WriteLi ne("Struct Array : " + structArray[0].X);
Console.WriteLi ne("Interface Array : " + interfaceArray[0].X);
Console.WriteLi ne("Class List : " + classList[0].X);
Console.WriteLi ne("Struct List : " + structList[0].X);
Console.WriteLi ne("Interface List : " + interfaceList[0].X);
}
}

public class MyClass : MyInterface
{
private int x;

public int X
{
get
{
return x;
}
set
{
x = value;
}
}
}

public struct MyStruct : MyInterface
{
private int x;

public int X
{
get
{
return x;
}
set
{
x = value;
}
}
}

public interface MyInterface
{
int X { get; set; }
}
On 14 May 2007 10:28:01 -0700, Zytan <zy**********@g mail.comwrote:
>This returns the following error:
"Cannot modify the return value of
'System.Collec tions.Generic.L ist<MyStruct>.t his[int]' because it is
not a variable"
and I have no idea why! Do lists return copies of their elements?
Why can't I change the element itself?

class Program
{
private struct MyStruct
{
private int myVar;
public int MyProperty
{
get { return myVar; }
set { myVar = value; }
}
}

private static List<MyStructli st = new List<MyStruct>( );

private static void Main(string[] args)
{
MyStruct x = new MyStruct();
x.MyProperty = 45;
list.Add(x);
list[0].MyProperty = 45; // <----------- ERROR HERE
}
}

Zytan
May 14 '07 #8
On May 14, 12:25 pm, Samuel R. Neff <samueln...@nom ail.comwrote:
If you declare your structure to implement an interface and then
declare the list as containing the interface instead of the structure,
then you can work with the structure (through the interface
implemented members) directly (interfaces allow you to pierce the
box).

Code sample below.

HTH,

Sam

------------------------------------------------------------
We're hiring! B-Line Medical is seeking .NET
Developers for exciting positions in medical product
development in MD/DC. Work with a variety of technologies
in a relaxed team environment. See ads on Dice.com.

public static void Test()
{
MyClass[] classArray = new MyClass[1];
MyStruct[] structArray = new MyStruct[1];
MyInterface[] interfaceArray = new MyInterface[1];
List<MyClasscla ssList = new List<MyClass>(1 );
List<MyStructst ructList = new List<MyStruct>( 1);
List<MyInterfac einterfaceList = new List<MyInterfac e>(1);

classArray[0] = new MyClass();
classList.Add(n ew MyClass());
interfaceArray[0] = new MyStruct();
structList.Add( new MyStruct());
interfaceList.A dd(new MyStruct());

classArray[0].X++;
interfaceArray[0].X++;
structArray[0].X++;
classList[0].X++;

// Cannot modify the return value of 'List<MyStruct> .this[int]'
// because it is not a variable
//structList[0].X++;
interfaceList[0].X++;

Console.WriteLi ne("Class Array : " + classArray[0].X);
Console.WriteLi ne("Struct Array : " + structArray[0].X);
Console.WriteLi ne("Interface Array : " + interfaceArray[0].X);
Console.WriteLi ne("Class List : " + classList[0].X);
Console.WriteLi ne("Struct List : " + structList[0].X);
Console.WriteLi ne("Interface List : " + interfaceList[0].X);
}

}

public class MyClass : MyInterface
{
private int x;

public int X
{
get
{
return x;
}
set
{
x = value;
}
}

}

public struct MyStruct : MyInterface
{
private int x;

public int X
{
get
{
return x;
}
set
{
x = value;
}
}

}

public interface MyInterface
{
int X { get; set; }

}
Now I'm curious: does the array MyInterface[] contain the actual
values, or does one incur boxing overhead when putting the value into
the array? In other words, is it an array of MyStruct, or an array of
boxes of MyStructs?

May 14 '07 #9
Bruce Wood <br*******@cana da.comwrote:
Now I'm curious: does the array MyInterface[] contain the actual
values, or does one incur boxing overhead when putting the value into
the array? In other words, is it an array of MyStruct, or an array of
boxes of MyStructs?
Boxes - the values are references, and have to be, given that you could
use a reference type implementation.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
May 14 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

14
5593
by: Dave | last post by:
Hello all, After perusing the Standard, I believe it is true to say that once you insert an element into a std::list<>, its location in memory never changes. This makes a std::list<> ideal for storing vertices of an arbitrary n-ary tree where a vertex contain pointers to its parent / children. These parent / child vertices need to stay put...
9
7868
by: Paul | last post by:
Hi, I feel I'm going around circles on this one and would appreciate some other points of view. From a design / encapsulation point of view, what's the best practise for returning a private List<as a property. Consider the example below, the class "ListTest" contains a private "List<>" called "strings" - it also provides a public...
0
7710
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7625
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7935
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8144
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
6313
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5519
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5244
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
1
2128
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1235
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.