0

Please compare these two codes. I can't understand why former one didn't work while latter one work perfectly.

// With loop - not work
for (int i = 0; i < 5; i++)
{
    Location l = new Location();
    l.Identifier = i.ToString();
    _locations.Add(l);
}
////

Dictionary<Location, Route> _paths = new Dictionary<Location, Route>();
foreach (Location loc in _locations)
{
    _paths.Add(loc, new Route(loc.Identifier));
}

Location start = new Location();
start.Identifier = "1";
_paths[start].Cost = 0;       //raised Key not exists error

Here is working version...

// Without Loop - it work
Location l1 = new Location();
l1.Identifier = "1";
_locations.Add(l1);

Location l2 = new Location();
l2.Identifier = "2";
_locations.Add(l2);

Location l3 = new Location();
l3.Identifier = "3";
_locations.Add(l3);
/////

Dictionary<Location, Route> _paths = new Dictionary<Location, Route>();
foreach (Location loc in _locations)
{
    _paths.Add(loc, new Route(loc.Identifier));
}

Location start = new Location();
start.Identifier = "1";
_paths[start].Cost = 0;

Any ideas? Thanks.

Edit: Location Class

public class Location

{
    string _identifier;
    public Location()
    {

    }

    public string Identifier
    {
        get { return this._identifier; }
        set { this._identifier=value; }
    }

    public override string ToString()
    {
        return _identifier;
    }
}
  • You should also post your Location class, and have a look here --> http://stackoverflow.com/questions/634826/using-an-object-as-a-generic-dictionary-key-in-net ;) – digEmAll Aug 23 '10 at 06:58
  • Thats right... You should post Location class also. Is Identifier member of Location class a string or something else? – Shekhar Aug 23 '10 at 07:03

4 Answers4

4

Neither should work unless you override Equals and GetHashCode in your Location class so that the Dictionary matches Location key objects based on equality of their Identifier rather than object equality.

Ian Mercer
  • 38,490
  • 8
  • 97
  • 133
0

Does the Location class implement GetHashCode? If not, you should override this and make sure it returns a unique int for each instance.

Mike Christensen
  • 88,082
  • 50
  • 208
  • 326
0

In addition to GetHashCode you need to override Equals as it is called when hash codes are reported equal, to conclude the objects equality. In isolation hash codes can only prove inequality. Non-equal objects can have equal hash codes; equal hash codes do not prove objects are equal.

vaso
  • 213
  • 2
  • 9
-1

Both the code pieces you have mentioned will not work. Try running your code tagged "Working version" again, it should throw the same exception as the first one.

Premkumar
  • 111
  • 1
  • 8