You can convert a string to an enum using the Enum.Parse() method. Here's how you can do it:
using System;
namespace ConsoleApp1
{
public class Program
{
public enum Days
{
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
}
public static void Main()
{
string userInput = "Tuesday";
try
{
Days day = ParseEnum<Days>(userInput);
Console.WriteLine("Converted enum value: " + day);
}
catch (ArgumentException)
{
Console.WriteLine("Invalid enum value");
}
Console.ReadLine();
}
public static TEnum ParseEnum<TEnum>(string value)
{
return (TEnum)Enum.Parse(typeof(TEnum), value);
}
}
}
This code snippet demonstrates converting the string "Tuesday"
to the enum value Days.Tuesday. The Enum.Parse() method takes two parameters: the type of the enum
(typeof(Days)) and the string representation of the enum value
(userInput).
Remember to handle exceptions if the string does not match any of the enum values to prevent runtime errors.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
You can convert a string to an enum using the Enum.Parse() method. Here's how you can do it:
This code snippet demonstrates converting the string "Tuesday" to the enum value Days.Tuesday. The Enum.Parse() method takes two parameters: the type of the enum (typeof(Days)) and the string representation of the enum value (userInput).
Remember to handle exceptions if the string does not match any of the enum values to prevent runtime errors.
Read more -
Convert int to enum in C#
How to combine two arrays without duplicate values in C#?
When to use Struct over Class in C#