C# | How to get hash code for the specified key of a Hashtable

Hashtable.GetHash(Object) method is used to get the hashcode of the specified key of a Hashtable object. This method is inherited from the Object Class.

Syntax:

protected virtual int GetHash(Object Key);

Exception: This method will give NullReferenceException if the key is null.

Below programs illustrate the use of above-discussed method:

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# Program to illustrate the 
// Hashtable.GetHash(Object) method
using System;
using System.Collections;
  
// Inheriting Hashtable as 
// Hashtable.GetHash(Object) 
// method is protected method
class HashCode : Hashtable {
      
    // Main Method
    static void Main(string[] args)
    {
          
        // creating object for HashCode as
        // to access protected methods we
        // have to create object for the 
        // derived class
        HashCode h = new HashCode();
          
        // Add Elements into Hashtable
        h.Add("1001", "Parek Shetty");
        h.Add("1002", "Deshmuk Narayan");
        h.Add("1003", "Ratan Kaalikaran");
          
        ICollection Key = h.Keys;
  
        foreach(string val in Key)
        {
              
            // printing Hashtable
            Console.Write(val + " : " + h[val]);
            Console.Write("\n");
              
            // printing hashcode with keys
            int hcode = h.GetHash(val);
              
            Console.Write(val + " : " + hcode);
            Console.Write("\n");
        }
    }
}

chevron_right


Output:

1002 : Deshmuk Narayan
1002 : 985757554
1001 : Parek Shetty
1001 : -1708895167
1003 : Ratan Kaalikaran
1003 : -1892225314

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# Program to illustrate the 
// Hashtable.GetHash(Object) method
using System;
using System.Collections;
  
class HashCode : Hashtable {
      
    // Main Method
    static void Main(string[] args)
    {
        HashCode h = new HashCode();
          
        // Adding elements
        h.Add('A', "Pritam Devadhya");
        h.Add('B', "Arjun Balachi");
        h.Add('C', "Timanad Panigrahi");
          
        ICollection Key = h.Keys;
          
        int hcode = h.GetHash('C');
          
        Console.Write("HashCode: " + hcode);
    }
}

chevron_right


Output:

HashCode: 4390979

Reference:



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.