Convert String to/from Enum in C# with Examples
This tutorial covers the following topics in C#:
- How to convert a String to Enum constants
- How to parse Enum to String in C#
- Convert all Enum constants to String using a for loop
Enum
is a custom special class type that holds a group of constant values, which can be either strings or numbers. You can refer to my other post on Converting Int to Enum in C#.
String
is a native predefined type in C# that stores a group of Unicode characters.
Automatic conversion is not possible due to different types of data.
Let’s declare Enum constants in C#, where Enum constants contain an int value.
public enum DAYS : int{
Monday = 1,
Tuesday = 2,
Wednesday = 3,
Thursday = 4,
Friday = 5,
Saturday = 6,
Sunday = 7,
}
How to Convert Enum to String in C#
The first method involves using the Enum.Parse()
method. Enum.Parse()
takes an Enum and a String, returning an object that needs to be cast to the .
using System;
public class Program
{
public static void Main()
{
var currentDay="Monday";
DAYS myday = (DAYS)Enum.Parse(typeof(DAYS),currentDay);
Console.WriteLine(myday);
}
}
If the string is null or empty, it throws an error.
Compilation error (line 7, col 7): Cannot assign <null> to an implicitly-typed variable
.
To handle this, you can check for null or empty before parsing.
The second method involves using Enum.GetName
, which returns the string value for an Enum.
DAYS myday=DAYS.Monday;
var str = Enum.GetName(typeof (DAYS), myday);
How to Convert String to Enum in C#
C# provides ToString()
on Enum values, which returns the string version of an Enum.
Here is an example
using System;
public class Program
{
public static void Main()
{
Console.WriteLine(DAYS.Tuesday.ToString());
}
}
public enum DAYS {
Monday,
Tuesday ,
Wednesday ,
Thursday ,
Friday ,
Saturday,
Sunday ,
}
For example, to iterate through Enum values and print the string version of Enum:
This approach uses a for loop to iterate from the start value of the Enum to its end, printing the string representation of each Enum value.
using System;
public class Program
{
public static void Main()
{
for (DAYS days = DAYS.Monday; days <= DAYS.Sunday; days++)
{
string day = days.ToString();
Console.WriteLine(day);
}
}
}
Conclusion
C# provides multiple ways to convert a String to/from an Enum.