Open In App

Getting the Hash Code of the Given Index in C#

Last Updated : 28 Nov, 2019
Improve
Improve
Like Article
Like
Save
Share
Report

The Index Structure is introduced in C# 8.0. It represents a type that can be used to index a collection or sequence and it can be started from the start or the end. You are allowed to find the hash code of the specified index with the help of the GetHashCode Method provided by the Index struct. This method returns the hash code of the specified index.

Syntax:

public override int GetHashCode();

Example 1:




// C# program to illustrate the 
// concept of the GetHashCode() method
using System;
  
namespace example {
  
class GFG {
  
    // Main Method
    static void Main(string[] args)
    {
        // Creating new indexes
        // Using Index() constructor
        var in1 = new Index(1, true);
        var in2 = new Index(3, false);
  
        // Getting the hash code
        // of the given index
        // Using GetHashCode() method
        var res1 = in1.GetHashCode();
        var res2 = in2.GetHashCode();
  
        // Displaying the index
        Console.WriteLine("Hash Code of Index: {0} is: {1} ", in1, res1);
        Console.WriteLine("Hash Code of Index: {0} is: {1} ", in2, res2);
    }
}
}


Output:

Hash Code of Index: ^1 is: -2 
Hash Code of Index: 3 is: 3 

Example 2:




// C# program to illustrate the concept
// of the GetHashCode() method
using System;
   
namespace example {
   
class GFG {
   
    // Main Method
    static void Main(string[] args)
    {
   
        // Creating and initializing an array
        string[] greetings = new string[] {"Hello", "Hola", "Namaste"
                                "Bonjour", "Ohayo", "Ahnyounghaseyo"};
   
        // Creating new indexes
        // Using Index() constructor
        var in1 = new Index(2, true);
        var in2 = new Index(3, false);
        var in3 = new Index(2, false);
   
        // Getting the hash code
        // of the given indexes
        // Using GetHashCode() method
        var res1 = greetings[in1].GetHashCode();
        var res2 = greetings[in2].GetHashCode();
        var res3 = greetings[in3].GetHashCode();
   
        // Displaying the index
        Console.WriteLine("Index: {0} Value: {1} HashCode: {2} ",
                                     in1, greetings[in1], res1);
   
        Console.WriteLine("Index: {0} Value: {1} HashCode: {2} ",
                                     in2, greetings[in2], res2);
   
        Console.WriteLine("Index: {0} Value: {1} HashCode: {2} ",
                                     in3, greetings[in3], res3);
    }
}
}


Output:

Index: ^2 Value: Ohayo HashCode: -1302855152 
Index: 3 Value: Bonjour HashCode: 399419679 
Index: 2 Value: Namaste HashCode: 1350085290 


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads