How to solve it: Struct In Collection has not been changed

I have a problem with structures.

I have this structure:

struct MyStruct { public int x; public int y; public MyStruct(int x,int y) { this.x = x; this.y = y; } } 

When I try to add this structure to a list like this:

 List<MyStruct> myList = new List<MyStruct>(); // Create a few instances of struct and add to list myList.Add(new MyStruct(1, 2)); myList.Add(new MyStruct(3, 4)); myList[1].x = 1;//<=====Compile-time error! 

I get this error:

 Compile-time error: Can't modify '...' because it not a variable 

Why am I getting this error and how to solve it?

+4
source share
1 answer

The structure is usually mutable, i.e. You can directly change the values โ€‹โ€‹of your members.

According to this website :

However, if a structure is used in a collection class, such as List, you cannot change its elements. A reference to an element by indexing into the collection returns a copy of the structure that you cannot modify. To change an item in a list, you need to create a new instance of the structure.

  List<MyStruct> myList = new List<MyStruct>(); // Create a few instances of struct and add to list myList.Add(new MyStruct(1, 2)); myList.Add(new MyStruct(3, 4)); myList[1].x = 1;//<=====Compile-time error! // Do this instead myList[1] = new MyStruct(1,myList[1].y); 

If you store structures in an array, you can change the value of one of the structs elements.

  MyStruct[] arr = new MyStruct[2]; arr[0] = new MyStruct(1, 1); arr[0].x= 5.0; // OK 
+4
source

Source: https://habr.com/ru/post/1469209/


All Articles