C# program 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#?
Submitted by Nidhi, on November 08, 2020

Here, we will print the hashcode of enum constants using GetTypeCode() method and then print them on the console screen.


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# program to get the hash-code of enum constants.

using System;

enum COLOR

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


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


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.

Comments and Discussions

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.