-1
public struct rectangle
{
   public decimal a;
}

that is my struct and i have a list of struct rectangles

list<rectangle> dataRectangle= new list<rectangle>();

now i have already added some structs into the list now i would like to change the value of a struct present in a list like

dataRectangle[0].a=0;

it says

cannot modify the return value ' list<form4.rectangle>.this[int] ' because it is not a variable

help why is this coming and is there another way to modify

  • If you really want to put mutable structs in a container, then use `array`. Everything else (list, etc) is just a pain. – Ivan Stoev Jun 29 '16 at 11:19
  • SOme duplciates here: http://stackoverflow.com/questions/51526/changing-the-value-of-an-element-in-a-list-of-structs, http://stackoverflow.com/questions/16679033/cannot-modify-struct-in-a-list. Why use a struct if you want to mutate it? – doctorlove Jun 29 '16 at 11:20

1 Answers1

2

A struct is a value type. So in contrast to a reference type like a class you don't pass around references to an instance, but pass around the value itself.

So what is returned from the indexer dataRectangle[0] is not a reference to your struct but a copy of that struct. And it's simply passed on the stack but is no variable itself.

To solve this, you can either declare your rectangle as class (which I would prefer for a mutable type:

public struct rectangle
{
   public decimal A {get; set;}
}

or you would (as ugly as it looks) have to do a reassignment like

dataRectangle[0] = new rectangle{a=0};
René Vogt
  • 43,056
  • 14
  • 77
  • 99
  • 1
    Can we please simply close the question as duplicate? We don´t want those simple question that have been answered thousand of times before here on SO – MakePeaceGreatAgain Jun 29 '16 at 11:17
  • @HimBromBeere I agree and already voted to close. I just can't get used to _first_ look for duplicates instead of simply answering. Anyway those questions are still search anchors to lead asking users to answers, so I don't think it's harmful to SO to leave this answer now. And I promise to try to remember to check for duplicates before answering in the future. – René Vogt Jun 29 '16 at 11:19