KeyNotFound Exception in CSsharp
        Posted  
        
            by C Patton
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by C Patton
        
        
        
        Published on 2010-03-14T17:09:01Z
        Indexed on 
            2010/03/14
            17:15 UTC
        
        
        Read the original article
        Hit count: 252
        
I'm about ready to bang my head against the wall
I have a class called Map which has a dictionary called tiles.
class Map
{
    public Dictionary<Location, Tile> tiles = new Dictionary<Location, Tile>();
    public Size mapSize;
    public Map(Size size)
    {
        this.mapSize = size;
    }
   //etc...
I fill this dictionary temporarily to test some things..
public void FillTemp(Dictionary<int, Item> itemInfo)
    {
        Random r = new Random();
        for(int i =0; i < mapSize.Width; i++)
        {
            for(int j=0; j<mapSize.Height; j++)
            {
                Location temp = new Location(i, j, 0);
                int rint = r.Next(0, (itemInfo.Count - 1));
                Tile t = new Tile(new Item(rint, rint));
                tiles[temp] = t;
            }
        }
    }
and in my main program code
Map m = new Map(10, 10);
m.FillTemp(iInfo);
Tile t = m.GetTile(new Location(2, 2, 0)); //The problem line
now, if I add a breakpoint in my code, I can clearly see that my instance (m) of the map class is filled with pairs via the function above, but when I try to access a value with the GetTile function:
    public Tile GetTile(Location location)
    {
        if(this.tiles.ContainsKey(location))
        {
            return this.tiles[location]; 
        }
        else
        {
            return null;
        }
    }
it ALWAYS returns null. Again, if I view inside the Map object and find the Location key where x=2,y=2,z=0 , I clearly see the value being a Tile that FillTemp generated..
Why is it doing this? I've had no problems with a Dictionary such as this so far. I have no idea why it's returning null. and again, when debugging, I can CLEARLY see that the Map instance contains the Location key it says it does not... very frustrating.
Any clues? Need any more info?
Help would be greatly appreciated :)
© Stack Overflow or respective owner