Why is Dictionary.ContainsKey returning False when the key is an int[]?

675 views Asked by At

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.

1

There are 1 answers

0
Super Jade On BEST ANSWER

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.