In C#, you can cast a string to an enum by using the Enum.Parse()
method. Here's an example:
Suppose you have an enum type called DaysOfWeek
, which contains the days of the week:
enum DaysOfWeek
{
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
}
And suppose you have a string called dayString
, which contains the name of a day of the week:
string dayString = "Tuesday";
To convert the string to an enum, you can use the Enum.Parse()
method, like this:
DaysOfWeek dayEnum = (DaysOfWeek)Enum.Parse(typeof(DaysOfWeek), dayString);
The Enum.Parse()
method takes two arguments: the type of the enum (in this case, DaysOfWeek
), and the string to parse (in this case, dayString
). The method returns an object of the specified enum type, which you can then cast to the enum type you need (in this case, DaysOfWeek
).
If the string does not match any of the enum values, Enum.Parse()
will throw an ArgumentException
. To handle this, you can use a try-catch
block to catch the exception and handle it appropriately.
Comments
Post a Comment