Saturday, April 4, 2009

Convert String To Enum Instance in C#

Converting a string to enum is quite easy one, but it need some attention when converting from string to enum. I will try to explain you how you can convert from a string to enum type. For this post i have same enum Type which is EmployeeType which i have used in my previous post which is Convert Integer To Enum Instance in C# .EmployeeType enum type consist of four named constants which are Manager, Grunt, Contractor and the VicePresident and i have set the integer value for the named constant which are 1, 2, 3 and 4 respectively.
enum EmployeeType
{
Manager = 1,
Grunt = 2,
Contractor = 3,
VicePresident = 4,
}
Below is the example code you can use to convert from string value to enum instant. In the first statement i have "Manager" string value to be converted from string to enum instant and i have used the Enum.Parse function to convert from string to enum instant. The Enum.Parse function will take the type of enum to which you want to create the output and the second one is the string value which is used to parse. The Enum.Parse has one overloaded function which will take a Boolean value either true of false. In the next statement i have used the overloaded function of the Enum.Parse function to give some information about the overloaded function to you people.
EmployeeType manager= (EmployeeType)Enum.Parse(typeof(EmployeeType),"Manager");
EmployeeType contractor = (EmployeeType)Enum.Parse(typeof(EmployeeType),"contRACtor",true);
Console.WriteLine("Volume Member: {0}\t Value: {1}", manager, (byte)Enum.Parse(typeof(EmployeeType), manager.ToString()));
Console.WriteLine("Volume Member: {0}\t Value: {1}", contractor, (byte)Enum.Parse(typeof(EmployeeType), contractor.ToString()));
Console.ReadKey();
As you can see in the above code that i have passed "contRACtor" and also pass the true value to the Enum.Parse function. Which mean that Enum.Parse function will ignore the case of the string and convert it to the respective enum Instant. And of course not forget to pass the type of enum to which you want to create the output.
Above code is simple one as we are converting the string value which are defined in the EmployeeType , what about if we pass the "Managers" or some other value which is not given in the EmployeeType, then for that case it will throw ArgumentException Exception. To avoid Argument Exception we have alternative ways to check if the string value exist in the enumeration or not. Below is the one way you can use this technique to avoid the Argument Exception.
string strValue = "Manager";
Boolean blnIsExist = Enum.IsDefined(typeof(EmployeeType), strValue);
if (blnIsExist)
{
EmployeeType manager = (EmployeeType)Enum.Parse(typeof(EmployeeType), strValue );
Console.WriteLine("Volume Member: {0}\t Value: {1}", manager, (byte)Enum.Parse(typeof(EmployeeType), manager.ToString()));
}
else
Console.WriteLine("Not Found");
In the code above i have use the Enum.IsDefined function to check the string value in the enumeration of EmployeeType. it will return true in the above case as i have pass right value to the IsDefined function which is the "Manager", by checking the Boolean value which is return by the IsDefined function we can avoid the argument exception. But using this techinque has a draw back ,which is if you pass the value which is in the enumeration say you pass the value "manager", the IsDefined function will return false for it as it didn't match with any names constant, because characters in the passed string must have the same case as the enumeration member name. To avoid such situation we can use use another technique by checking the string value in the enumeration. Here is the list of code you can use over come the case sensitive of the input string.
string strValue = "manager";
Boolean blnIsExist =CheckStringValueInEnum(strValue);
if (blnIsExist)
{
EmployeeType manager = (EmployeeType)Enum.Parse(typeof(EmployeeType), strValue,true );
Console.WriteLine("Volume Member: {0}\t Value: {1}", manager, (byte)Enum.Parse(typeof(EmployeeType), manager.ToString()));
}
else
Console.WriteLine("Not Found");


private static Boolean CheckStringValueInEnum(string pstrValue)
{
foreach (string strEmployeeType in Enum.GetNames(typeof(EmployeeType)))

if (string.Compare(strEmployeeType, pstrValue, true) == 0)
return true;
return false;
}
In the above code i have passed "manager" string value to the function CheckStringValueInEnum which will check the passed string in the EmployeeType enumeration by comparing the passed string to the string value of the enumeration names constant. In the CheckStringValueInEnum function i have used the Enum.GetNames function which will return the string array of names . I have used the string.compare function by passing the two string value and the third one which is of type Boolean to indication of ignoring the case of the string characters. Here it will return true and i have also pass true to the Enum.Parse method to ignore the case of the input string so that string parsing can take place by ignoring the case of the input string.By using this technique we can avoid the exception. As i have console test application and the main function of the console is static , so the CheckStringValueInEnum is also static so that it can be called in the main function.
All and any comments / bugs / suggestions are welcomed!


No comments: