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



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;

.



Relevant Pages

  • Re: List of enumerators?
    ... I have various lists I want to go through, ... want to control that with a list of enumerators. ... For reference types, a copy ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: List Item paragraph style
    ... That's the point -- I haven't been able to figure out how to modify what is ... there and permanently modify the template. ... When I click the style group it brings up "list paragraph" but my ... paragraph spacing used in lists. ...
    (microsoft.public.word.numbering)
  • Re: List Item paragraph style
    ... If you want to set text formatting defaults, you need to modify a style. ... Just add the styleto the blank document template, ... If you create a list style *and* attach a paragraph style to each ... Is it unreasonable to want to control the way my lists appear without ...
    (microsoft.public.word.numbering)
  • Re: List Item paragraph style
    ... You can modify the built-in styles. ... you check the box for "Add to template" or whatever is the ... If you create a list style *and* attach a paragraph style to each ... paragraph spacing used in lists. ...
    (microsoft.public.word.numbering)
  • Re: Outline Numbering for Headings in 2007
    ... Modify numbering style via Modify Style DOES NOT provide multilevel ... Note that the safest way to set up numbered lists in Word 2007 is to ...
    (microsoft.public.word.numbering)

Loading