tags:

views:

54

answers:

4

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;
    }
}
A: 

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

Mike
Thanks for your tips. Implemented GetHashCode and Equals. It's work now.
Hnin Wai Lwin
A: 

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
+1  A: 

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.

Hightechrider
A: 

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
Thanks for your tips. Implemented GetHashCode and Equals. It's work now.
Hnin Wai Lwin