TypeCast/Convert a String Value to Enum value
There may be a situation where we need to convert our string value to an Enumeration value. For Converting a string to Enumeration value use Enum.Parse();
Parse() : This method takes the following arguments
Type of enumeration you want to convert
String that you want to convert
Example
public enum WeekWorkingDays
{
Monday=1,
Tuesday=2,
Wednesday=3,
Thursday=4,
Friday=5
}
//btnClick event
string strCurrentWorkingDay = “Wednesday”;
WeekWorkingDays CurrentDay = WeekWorkingDays.Monday;
try
{
CurrentDay = (
WeekWorkingDays)Enum.Parse(typeof(WeekWorkingDays), strCurrentWorkingDay);
switch(CurrentDay)
{
case WeekWorkingDays.Monday:
case WeekWorkingDays.Wednesday:
//Project meeting will be on 9 to 10
break;
case WeekWorkingDays.Friday:
//Project meeting will be on 4 to 5 PM
break;
}
}
catch
{
//Invalid value
}
Note: Enum.Parse() is a case sensiteive. Therfore if strCurrentWorkingDay value is wednesday insetead of Wednesday,
the Parse.Enum will throw an Exception.
To make the Enum.Parse function to accept the case insensitve data use the Overload method of Enum.Parse as follows.
CurrentDay = (
WeekWorkingDays)Enum.Parse(typeof(WeekWorkingDays), strCurrentWorkingDay,true);
Parameters:
Enumeration Type
String to be converted
Boolean value to consider the case sensitive data