When we Get true while we use IsFixedSize Method in hashtable in C#?

117 Views Asked by At

so, I tried one program in C# of hashtable whenever I give a fixed size to the hashtable and then try out a method IsFixedSize it gives False. Then what is the reason behind it? (if size is fixed then also give false). Give an example which showcases true if we fetch the fixed-sized method.

using System;
  using System.Collections;
     class Program 
      {
           static void main()
            { 
                 Hashtable fixedSizeHashtable = new Hashtable(3)
                 {
                   { 1, "One" },
                   { 2, "Two" },
                   { 3, "Three" }
                 };
                 Console.WriteLine(fixedSizeHashtable.IsFixedSize); 
             }
        }
2

There are 2 best solutions below

2
Mustafa Özçetin On

The capacity value that you pass to the Hashtable constructor has nothing to do with the IsFixedSize property. In other words, the capacity value does not put an upper limit or does not fix the item size of a Hashtable. When you add items, the capacity value is automatically increased as required based on the load factor. (Other collections may double the item count on each resize). For example you can still add the fourth item to your Hashtable when your initial capacity is three:

fixedSizeHashtable.Add(4, "Four");

The main concern of using the initial capacity in the constructor is to eliminate the need to perform redundant resizing operations when you know the approximate item count initially.

Look at the Hashtable constructor for details.

0
Progman On

The IsFixedSize property on the Hashtable class is a requirement from the IDictionary.IsFixedSize property from the IDictionary interface this Hashtable class is implementing. The Hashtable class allows dynamically adding and removing entries, which means the size cannot be fixed, therefore this property returns false. But since the class is not sealed, there can be other classes deriving from Hashtable which could have a fixed size.