C# - How to Get Name of Enum Constant from Given Value?

Here, we are going to learn how to print the name of enum constant based on an integer value in C#? By Nidhi Last updated : March 29, 2023

Get Name of Enum Constant from Given Value

To get name of Enum constant from given value, we use Enum.GetName() method. This method accepts an integer value and returns the Enum constant.

C# program to print the name of enum constant based on an integer value

The source code to print the name of enum constant based on integer value is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

// C# program to print the name of enum 
// based on an integer value

using System;

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

class EnumDemo {

  static void Main(string[] args) {
    Console.WriteLine("Name is: {0}", Enum.GetName(typeof (COLOR), 2));
    Console.WriteLine("Name is: {0}", Enum.GetName(typeof (COLOR), 5));
  }
}

Output

Name is: YELLOW
Name is: BLUE
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 the Main() method. The Main() method is the entry point for the program.

In the Main() method, we called to get the name of enum constants using the GetName() method of Enum class and print the name on the console screen.

C# Enum Class Programs »

Comments and Discussions!

Load comments ↻





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