Z
Z
Zefirot2022-02-05 14:03:39
C++ / C#
Zefirot, 2022-02-05 14:03:39

Why does an array work like a dictionary?

There were some problems with dictionaries due to the fact that the values ​​​​changed somewhere and at the same time they changed in the dictionaries themselves from where the data was taken initially, since these are links ...
So I started using an array, but then the same problem occurred

[Serializable] public class ClassTest{
  private int a; public int Life{ get{ return a; } set{ a = value; }}
  private string b; public string Name{ get{ return b; } set{ b = value; }}
  ............
  }
......
public ClassTest[] ArrayClassTest;
....
ArrayClassTest[0].Life = 100;
ArrayClassTest[0].Name = "Test";
ArrayClassTest[1].Life = 100;
ArrayClassTest[1].Name = "Test";
.....
ArrayClassTest[0].Life = 5;
Debug.Log(ArrayClassTest[0].Life);
Debug.Log(ArrayClassTest[1].Life);

conclusion
5
5

Why so, how to avoid it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
@
@insighter, 2022-02-05
@Zefirot

The point is certainly not where you store the data - an array, a dictionary, a list, but what you store and how you manipulate it.
Let's say you are dealing with a class

public class Point{
  public int X{ get; set;}
  public int Y{ get; set;}
}

var points = new Point[1];
var point = new Point();
points[0] = point; // points[0] и point указывают на один и тот же объект
points[0].X = 10; // point.X == 10

Because the class is a reference (mutable - also matters) data type.
Another example:
public struct StructPoint{
  public int X{ get; set;}
  public int Y{ get; set;}
}
var point = new StructPoint();
points[0] = point; // points[0] и point имеют одинаковое значение! т.е. (points[0] == point) но ссылаются на разные области памяти
points[0].X = 10; // point.X == 0

Because a struct is a value type.
For strings, the behavior is similar to structs, even though they are references. Because strings are immutable, when a string changes, a new one is actually created.
https://metanit.com/sharp/tutorial/2.16.php

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question