C# - Convert String to Enum
Converting a string to an enum in C# is the process of transforming a text-based representation (the string) into a corresponding value of an enumeration (enum) type. This is done to work with predefined, meaningful values instead of plain text, improving code clarity and type safety.
Why Convert a String to Enum?
There are scenarios where you might receive data as strings, such as user inputs or data from external sources, and you want to work with these values as enums for better type safety and code clarity. Converting strings to enums allows you to work with predefined, meaningful values instead of plain text.
Consider an example where we have an enum called DaysOfWeek
:
enum DaysOfWeek
{
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday
}
Now, suppose we receive a string containing the name of a day and want to convert it to the corresponding enum value:
using System;
class Program
{
static void Main()
{
string inputDay = "Wednesday";
DaysOfWeek day = ConvertToEnum(inputDay);
Console.WriteLine("The corresponding enum value is: " + day);
}
static DaysOfWeek ConvertToEnum(string day)
{
return Enum.Parse<DaysOfWeek>(day);
}
}
Output
If you run this program, the output will be:
The corresponding enum value is: Wednesday
In this example, we successfully converted the string "Wednesday" into its corresponding DaysOfWeek enum value, demonstrating the usefulness of converting strings to enums in C#.
Converting a String to Enum Using Enum.TryParse in C#
You can convert a string to an enum in C# using the Enum.TryParse
method. This approach is safer because it handles potential parsing errors gracefully without throwing exceptions.
using System;
enum DaysOfWeek
{
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday
}
class Program
{
static void Main()
{
string inputDay = "Wednesday";
if (Enum.TryParse(inputDay, out DaysOfWeek day))
{
Console.WriteLine("Successfully converted: " + day);
}
else
{
Console.WriteLine("Failed to convert the string to an enum.");
}
}
}
Output
If you run this program with the inputDay
set to "Wednesday," it will print:
Successfully converted: Wednesday
If you change the inputDay
to an invalid value like "InvalidDay," it will print:
Failed to convert the string to an enum.
Using Enum.TryParse
is a robust way to convert strings to enums while handling potential errors effectively.