Inserting twice the same key in a HashTable, how is that possible?
<p>I am trying to understand how works the key sorting / insertion check in a hashtable.
I've understood that when I'm adding an object to a hashtable, it checks at runtime that there isn't the same key already entered in there.</p>

<p>In my test, I've 2 hashtables which keys are filled in with:
1- Integers
2- An object which I've overriden the GetHashCode method to return always 1.</p>

<p>My issue here: while the first test is breaking when adding the same int key, the second test isn't! How come? The hashcodes that should be checked at the insertion are all returning 1.</p>

<p>Thank you in advance!</p>

<hr>

<p>My code:</p>

<pre><code>class Collections
{
    public Collections()
    {
        // Testing a hashtable with integer keys
        Dictionary&lt;int, string&gt; d1 = new Dictionary&lt;int, string&gt;();
        d1.Add(1, "one");
        d1.Add(2, "two");
        d1.Add(3, "three");
        // d1.Add(3, "three"); // Cannot add the same key, i.e. same hashcode
        foreach (int key in d1.Keys)
            Console.WriteLine(key);

        // Testing a hashtable with objects returning only 1 as hashcode for its keys
        Dictionary&lt;Hashkey, string&gt; d2 = new Dictionary&lt;Hashkey, string&gt;();
        d2.Add(new Hashkey(1), "one");
        d2.Add(new Hashkey(2), "two");
        d2.Add(new Hashkey(3), "three");
        d2.Add(new Hashkey(3), "three");
        for (int i = 0; i &lt; d2.Count; i++)
            Console.WriteLine(d2.Keys.ElementAt(i).ToString());

    }


}

/// &lt;summary&gt;
/// Creating a class that is serving as a key of a hasf table, overring the GetHashcode() of System.Object
/// &lt;/summary&gt;
class Hashkey
{
    public int Key { get; set; }

    public Hashkey(int key)
    {
        this.Key = key;
    }

    // Overriding the Hashcode to return always 1
    public override int GetHashCode()
    {
        return 1;
        // return base.GetHashCode();
    }

    // No override
    public override bool Equals(object obj)
    {
        return base.Equals(obj);
    }

    // returning the name of the object
    public override string ToString()
    {
        return this.Key.ToString();
    }        
}
</code></pre>

<p>}</p>
