1

I have a Hashtable and I want to put check whether the Hashtable has key or not before adding a key in Hashtable. As adding a duplicate key in Hashtable throwing exception. Basically I want to override Hashtable's virtual 'Add' method and put a check in it. I dont know how can I override Add method.

Please help me to write override method.

Nikunj.Patel
  • 87
  • 1
  • 10
  • 1
    Why do you still use a `HashTable`? Use a `Dictionary`. However, use [`ContainsKey `](https://msdn.microsoft.com/en-us/library/system.collections.hashtable.containskey(v=vs.110).aspx) – Tim Schmelter Sep 30 '15 at 13:50
  • Actually its a older code and can not replace it for now. Replacement require so much efforts. – Nikunj.Patel Sep 30 '15 at 13:54
  • In project on hundreds of place we are adding key in Hashtable. But now at many places it may add duplicate key. and at that time it throws exception. I want to avoid this exception and want to put only one common check to reduce efforts. – Nikunj.Patel Sep 30 '15 at 14:05

2 Answers2

0

You can use ContainsKey.

Another way is to use the Item indexer-property which adds new keys and updates existing.

var ht = new System.Collections.Hashtable();
ht["test"] = "foo"; // added
ht["test"] = "bah"; // updated

However, you should consider to replace your old and redundant Hashtable with a generic Dictionary<Tkey, Tval>. Why?

Community
  • 1
  • 1
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
0

The Add method of the Hashtable class is overridable. So try this:

class MyHashTable : Hashtable
{
    public override void Add(object key, object value)
    {
        try
        {
            base.Add(key, value);
        }
        catch
        {
            // whatever
        }
    }
}
G. Drakos
  • 21
  • 2