Convert String to/from Enum in C# with examples
This tutorial explains about following things in C#
-
How to convert String to Enum constants
-
How to parse Enum to String in C Sharp?
-
Convert all Enum constants to String using for loop
Enum
is a custom special class type to have a group of constant values. the values can bestrings
ornumbers
.You can check my other post on Converting Int to Enum in CSharp
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#, 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 way, using Enum.parse() method Enum.parse() takes Enum and String and returns an object, cast this to Enum
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
The second way, Enum.GetName 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 and 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 Enum and print the string version of Enum.
Using for Loop, Iteration starts with Enum start value, increment enum until reaches end enum constants.
Finally, Print the Enum string 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);
}
}
}