none
System.Collections.Hashtable - How to obtain a value by a key?

    Question

  • Hello, everybody.

    I've just look through all documentation, concerning System.Collections.Hashtable in msdn.
    I can't understand, is there any interface function of Hashtable to obtain directly a value by a key?
    I always thought, it's a basic functionality of any hash.
    May be, I'm mistaken, looking for it.
    Help me, please, anybody.

    In advance, thanks.
    Tuesday, November 13, 2007 10:24 AM

Answers

  • Yes, you are absolutely ight

     

    hash["key1"] return object type.

    You can typecast according to the type of object you pass

     

    Regards,

    Manju Sandhu

    Tuesday, November 13, 2007 12:09 PM

All replies

  • Hi,

     

    Just try this code

     

     

    System.Collections.Hashtable hash = new System.Collections.Hashtable();

    hash.Add("key1", "value1");

    string value = hash["key1"].ToString();  //you will get the value corresponding to key1

     

     

    Regards,

    Manju Sandhu

    Tuesday, November 13, 2007 11:23 AM
  • Thank you very much for your answer, Manju Sandhu.

    And if I need to save not string value, a value of my own type, some object.
    Is it also possible to obtain my object? So, may be this way:

    System.Collections.Hashtable hash = new System.Collections.Hashtable();

    MyType myVar = new MyType();

    hash.Add("key1", myVar);

    MyType value = (MyType)hash["key1"];



    Yes?
    Tuesday, November 13, 2007 12:03 PM
  • Yes, you are absolutely ight

     

    hash["key1"] return object type.

    You can typecast according to the type of object you pass

     

    Regards,

    Manju Sandhu

    Tuesday, November 13, 2007 12:09 PM
  • Hi!

    You could also use the Generic class Dictionary instead of HashTable, which does not need casting. Some sources say that Dictionary works faster than HashTable. Dictionary is available from .NET 2.0. You can add any kind of type as a key, not just string. This can be useful sometimes.

    Dictionary<string, MyClass> dictionary = new Dictionary<string, MyClass>();
    dictionary.Add( "object1", new MyClass() );
    MyClass object1 = dictionary["object1"];
    Tuesday, November 13, 2007 12:58 PM