Open In App

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

Improve
Improve
Like Article
Like
Save
Share
Report

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:




// 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");
        }
    }
}


Output:

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

Example 2:




// 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);
    }
}


Output:

HashCode: 4390979

Reference:



Last Updated : 01 Feb, 2019
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads