René Beneš
René Beneš

Reputation: 468

C# Dictionary always returns last value

I have created dictionary and inserted 3 fields to it:

Dictionary<string, Map> targets = new Dictionary<string, Map>();
targets.Add("Pláž - střed", new Map("Pláž - sever", "Vrak letadla", "Džungle", "Vrak letadla"));
targets.Add("Vrak letadla", new Map("Pláž střed", "nothing", "Roští", "nothing"));
targets.Add("Roští", new Map("nothing", "nothing", "Tenký lesík", "Vrak letadla"));

When I tried to get field targets[Pláž - sever], map constructor parameters contained "nothing", "nothing", "Tenký lesík", "Vrak letadla" - value of the last field, value is the same for 2nd and 3rd field. Can you please help me solve that problem? I need 1st field to return its value, and not the value of the third field.

Upvotes: 0

Views: 232

Answers (3)

Embedd_0913
Embedd_0913

Reputation: 16555

You have not added any item in the dictionary with the Key "Pláž - střed"so you can't get that item coz it's simply not available.

So try to add an item with "Pláž - střed" key and then access it.

Upvotes: 0

galets
galets

Reputation: 18472

What you need to do is:

var a1 = new Map("Pláž - sever", "Vrak letadla", "Džungle", "Vrak letadla"));
var a2 = new Map("Pláž střed", "nothing", "Roští", "nothing"));

run this code in debugger and inspect values of a1 and a2. Chances are something is messed up with your Map class, such as fields declared static or something else of that nature

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500575

Your question is a little odd to start with - but I suspect you'll find that your Map class has static fields instead of instance fields. That would mean you've got one set of fields related to the type, and not to any particular instance of the type... so every time you overwrite the fields, you're losing all your previous data.

Just a guess though...

Upvotes: 5

Related Questions