Reputation: 11
I'm working on some map generation, but I have run into an issue. Below is the simplified code. It returns False whilst it should return True.
static Dictionary<int[], Tile> map = new Dictionary<int[], Tile>();
static bool GenerateMap()
{
for (int y = 0; y < 3; y++)
{
for (int x = 0; x < 3; x++)
{
Tile tile;
int[] i = {x, y};
if(map.ContainsKey(i))
{
tile = map[i];
Console.WriteLine("Contains!");
}
else
{
tile = new Tile();
tile.Generate();
map.Add(i, tile);
}
}
}
int[] z = {0,0};
if (map.ContainsKey(z)) return true;
return false;
}
I have tried Dictionary.TryGetValue() and Try / Catch, but neither worked.
Upvotes: 0
Views: 733
Reputation: 6345
Change this line:
static Dictionary<int[], Tile> map = new Dictionary<int[], Tile>();
Make the dictionary key a KeyValuePair or a ValueTuple instead of an int[]
:
static Dictionary<KeyValuePair<int, int>, Tile> map = new Dictionary<KeyValuePair<int, int>, Tile>();
or
static Dictionary<(int x, int y), Tile> map = new Dictionary<(int x, int y), Tile>();
Then use it throughout your code.
KeyValuePairs and ValueTuples are value types. You can check these for equality in the usual ways. ContainsKey
will work as expected.
An array is a reference type in C#. By default, no 2 arrays will ever be equal to each other, unless they are the same object.
Upvotes: 1