Answer the question
In order to leave comments, you need to log in
How to get values by new key instance in dictionary?
Hello. There is a list of objects that need to be stored in an array with the ability to find them by coordinates, I decided to write them to a dictionary and set a class with two-dimensional coordinates as a key, but when I try to get a value from a new key instance, an error pops up that the value was not found. How can the problem be solved? Save more links?
public class CellPos
{
public int x;
public int y;
}
...
public static Dictionary<CellPos, Cell> CellArray = new Dictionary<CellPos, Cell>();
...
CellArray.ContainsKey(new CellPos(1, 1));//false
Answer the question
In order to leave comments, you need to log in
Read how the Dictionary works and why you need GetHashCode()
and Equals()
.
So far, you can only find the same instance, not "by coordinates".
The simplest option is to declare CellPos as a record:
public record struct CellPos(int X, int Y); //record struct, тк объект маленький и очень похож на value-object
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question