Reputation: 554
I have a
Dictionary<NodePair, string> repo;
I have implemented the
GetHashCode(), Equals()
on the
NodePair
When I try to search for a key using
if(Repo.ContainsKey(new NodePair(OneTree.Root, AnotherTree.Root)))
it return false, however, when I do
foreach (NodePair pair in Repo.Keys)
if (pair.Equals(new NodePair(OneTree.Root, AnotherTree.Root)))
Console.WriteLine();
The debugger stops at the
Console.WriteLine()
same thing happened when I do
foreach (NodePair pair in Repo.Keys)
if (pair.GetHashCode() == (new NodePair(OneTree.Root, AnotherTree.Root)).GetHashCode())
Console.WriteLine();
So why the hack that ContainsKey() return false?????????
Edit put everything together:
foreach (NodePair pair in Repo.Keys)
if (pair.Equals(new NodePair(OneTree.Root, AnotherTree.Root)))
Console.WriteLine();
foreach (NodePair pair in Repo.Keys)
if (pair.GetHashCode() == (new NodePair(OneTree.Root, AnotherTree.Root)).GetHashCode())
Console.WriteLine();
if (Repo.ContainsKey(new NodePair(OneTree.Root, AnotherTree.Root)))
Console.WriteLine();
The first two Console.WriteLine()
hit and last one did not. Anyone can explain?
Upvotes: 0
Views: 60
Reputation: 26989
It is implemented like:
private int FindEntry(TKey key)
{
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
if (buckets != null)
{
int hashCode = comparer.GetHashCode(key) & 0x7FFFFFFF;
for (int i = buckets[hashCode % buckets.Length]; i >= 0; i = entries[i].next)
{
if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key)) return i;
}
}
return -1;
}
You can see the full source code for Dictionary if you want because it is available online. If you want to debug it, please see how to debug .NET code.
Upvotes: 2