Pages

Sunday, March 17, 2013

C#: Using HashTable

public void HashTable()
        {
            Hashtable hash = new Hashtable();
            hash.Add("Name1", "Alex");
            hash.Add("Name2", "Peter");
      
           //Gives the value of key Name2
             Console.WriteLine(hash["Name2"].ToString());

           //Check Name1 is on list
            Console.WriteLine(hash.Contains("Name1").ToString());

            //Remove Name2 key/value and check if it still contains.
            hash.Remove("Name2");
            Console.WriteLine(hash.Contains("Name2").ToString());

            try
            {
               //To display an item already removed from list and catched by exception.
                Console.WriteLine(hash["Name2"].ToString());
            }
            catch (NullReferenceException)
            {
                Console.WriteLine("The key value missing");
            }

           //Add two more value to list
            hash.Add("Name2", "Sam");
            hash.Add("Name3", "Kite");
          
           //To iterates the items in hashtable.
            IDictionaryEnumerator enumr=hash.GetEnumerator();
            while (enumr.MoveNext())
            {
                Console.WriteLine(enumr.Key.ToString());
            }
        }

Output:Peter
            True
            False
            The key value missing
            Name1
            Name2
            Name3

No comments:

Post a Comment