C# - How to Get the Hash-Code of Enum Constants?

Here, we are going to learn how to get the hash-code of enum constants in C#? By Nidhi Last updated : March 29, 2023

Get the Hash-Code of Enum Constants

To get the hash code of Enum constants, we use GetTypeCode() method.

C# program to get the hash-code of enum constants

The source code to get the hash-code of enum constants is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

// C# - How to Get the Hash-Code of Enum Constants?

using System;

enum COLOR {
  RED,
  GREEN,
  YELLOW,
  BLACK,
  WHITE,
  BLUE
}

class EnumDemo {
  static void PrintHashCode(COLOR color) {
    switch (color) {
    case COLOR.RED:
      Console.WriteLine("Color is Red,    hashcode: " + COLOR.RED.GetHashCode());
      break;
    case COLOR.GREEN:
      Console.WriteLine("Color is Green,  hashcode: " + COLOR.GREEN.GetHashCode());
      break;
    case COLOR.YELLOW:
      Console.WriteLine("Color is Yellow, hashcode: " + COLOR.YELLOW.GetHashCode());
      break;
    case COLOR.BLACK:
      Console.WriteLine("Color is Black,  hashcode: " + COLOR.BLACK.GetHashCode());
      break;
    case COLOR.WHITE:
      Console.WriteLine("Color is White,  hashcode: " + COLOR.WHITE.GetHashCode());
      break;
    case COLOR.BLUE:
      Console.WriteLine("Color is Blue,   hashcode: " + COLOR.BLUE.GetHashCode());
      break;
    }
  }
 
  static void Main(string[] args) {
    PrintHashCode(COLOR.RED);
    PrintHashCode(COLOR.GREEN);
    PrintHashCode(COLOR.BLUE);
  }
}

Output

Color is Red,    hashcode: 0
Color is Green,  hashcode: 1
Color is Blue,   hashcode: 5
Press any key to continue . . .

Explanation

In the above program, we created an enum COLOR that contain constants with color names. Here, we also created a class EnumDemo that contains two static methods PrintHashCode() and Main().

In the PrintHashCode() method, we created a switch block, here we printed the hash-code of color constants based on enum constant passed into the method.

In the Main() method, we called the PrintHashCode() method with different values of a COLOR enum.

C# Enum Class Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.