Re: List<> of struct with property. Cannot change value of property. why?
- From: Bruce Wood <brucewood@xxxxxxxxxx>
- Date: 14 May 2007 10:46:50 -0700
On May 14, 10:28 am, Zytan <zytanlith...@xxxxxxxxx> wrote:
This returns the following error:
"Cannot modify the return value of
'System.Collections.Generic.List<MyStruct>.this[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<MyStruct> list = 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;
.
- Follow-Ups:
- References:
- Prev by Date: Re: Which process is using a file?
- Next by Date: Re: Tracking a memory leak.
- Previous by thread: List<> of struct with property. Cannot change value of property. why?
- Next by thread: Re: List<> of struct with property. Cannot change value of property. why?
- Index(es):
Relevant Pages
|
Loading