views:

45

answers:

2

Hi All, I am trying to fix the size of the Hashtable with following code.

       Hashtable hashtable = new Hashtable(2);

        //Add elements in the Hashtable
        hashtable.Add("A", "Vijendra");
        hashtable.Add("B", "Singh");
        hashtable.Add("C", "Shakya");
        hashtable.Add("D", "Delhi");
        hashtable.Add("E", "Singh");
        hashtable.Add("F", "Shakya");
        hashtable.Add("G", "Delhi");
        hashtable.Add("H", "Singh");
        hashtable.Add("I", "Shakya");
        hashtable.Add("J", "Delhi");

I have fix the size of this Hashtable is 2 but I can add more than 2 elements in this, why this happen, I am doing somthing wrong?

I have tried to find out is this Hashtable have fix size of not with hashtable.IsFixedSize, it always returns false

Please tell me where I am wrong, or there is another way..

+1  A: 

Once you've added all the elements you need, you need to implement a read-only version of IDictionary that you can then use to disallow altering existing entries (look at subclassing Hashtable, and overriding all the methods/properties which alter values to throw NotSupportedException). You can then override IsReadOnly and IsFixedSize to return whatever values you need.

I would also recommend you use the generic Dictionary<TKey, TValue> instead of Hashtable, as you get better compile-time safety and better performance with value types. However, you would have to create your own read-only implementation of IDictionary<TKey, TValue>, as none of the Dictionary methods are virtual.

thecoop
A: 

The HashTable constructor overload that takes an int capacity parameter uses it only as a hint from you as to how many values it should be able to hold. This can improve the speed and memory consumption of the HashTable as it is populated, but it can grow to hold more values than this initial capacity. That is why you can add more than 2 values.

bbudge