How to Convert Enum to a String in C#
Enumerations are useful for defining a set of related constants, especially when the values of the constants have meaning beyond just their numerical value. This makes the code easier to read and maintain, as it provides a more descriptive way of representing values compared to using integer values directly. Here are two ways to convert enum to a string in C#:
Through Enum.GetName Method
The Enum.GetName() is used to retrieve the name of an enumerated constant as a string and takes in the enumeration type and the enumerated constant value as arguments, the following example demonstrates its use:
namespace EnumToString
{
enum Color
{
Yellow,
Pink,
White
}
class Program
{
static void Main(string[] args)
{
Color color = Color.White;
string enum_to_string = Enum.GetName(color);
Console.WriteLine("Enum value to String is: " + enum_to_string);
}
}
}
Here, we first define an enumeration named Color with three constants: Yellow, Pink, and White. Then, we create a variable of type Color named color and assign it the value Color.White.
Output
Here is the execution of the example code we used above along with its output:
Through Enum.ToString Method
The Enum.ToString method is used to convert an enumerated constant to its string representation. The method takes in the enumerated constant as an argument. The following example demonstrates its use:
namespace EnumToString
{
enum Color
{
White,
Yellow,
Blue
}
class Program
{
static void Main(string[] args)
{
Color color = Color.Yellow;
string enum_to_string = color.ToString();
Console.WriteLine("Enum value to String is: " + enum_to_string);
}
}
}
Here, we first define an enumeration named Color with three constants: White, Yellow, and Blue. Then, we create a variable of type Color named color and assign it the value Color.Yellow. Finally, we use the Enum.ToString method to convert color to a string.
Output
Here is the execution of the example code we used above along with its output:
Conclusion
Both the Enum.GetName method and the Enum.ToString method provide ways to convert an enum to a string in C#. The Enum.GetName method is useful when you have the enumerated constant value and need to retrieve its string representation, while the Enum.ToString method is useful when you have the enumerated constant itself.