Jasper Catthoor
Jasper Catthoor

Reputation: 625

C# An item with the same key has already been added

Even though I'm checking whether the map already contains the key just before I add it, I receive this error..

if (ShortBuffer.ContainsKey(GetTuple(data))) return;
ShortBuffer.Add(GetTuple(data),                 <----- ERROR OCCURS HERE
    new Tuple<Timer, int, bool, Data>(
        new Timer(Convert.ToInt32(Ini.ReadValue("intervals", "clientbuffershort"))), 0, false, data));

The GetTuple method:

private static Tuple<string, string, string> GetTuple(Data data)
{
    return new Tuple<string, string, string>(data.AucxisErrorId, data.ClientId, data.Area);
}

Any thoughts? Thanks!

Upvotes: 2

Views: 2085

Answers (1)

Maurits van Beusekom
Maurits van Beusekom

Reputation: 5989

First of all the GetTuple method returns a new instance every time you call it. It might contain the same data but they are still different objects. So the first step I would do is change the code to this:

var tuple = GetTuple(data);
if (ShortBuffer.ContainsKey(tuple)) return;

ShortBuffer.Add(tuple, new Tuple<Timer, int, bool, Data>(
    new Timer(Convert.ToInt32(Ini.ReadValue("intervals", "clientbuffershort"))), 0, false));

This makes sure you are atleast comparing and adding the exact same object to the map.

Second make sure the Tuple class implements the IEquatable<T> interface. This way you can be sure the contents of the Tuple objects are compared and not the memory address of where the objects are stored (since they differ from each other). More information on how to implement the IEquatable<T> interface can be found here: https://msdn.microsoft.com/en-us/library/ms131187(v=vs.110).aspx

Upvotes: 1

Related Questions