Try to parse number or string to enum in CSharp
Description
The following code shows how to try to parse number or string to enum.
Example
//from w w w. j a v a 2 s . co m
using System;
[Flags] enum Colors { None=0, Red = 1, Green = 2, Blue = 4 };
public class Example
{
public static void Main()
{
string[] colorStrings = { "0", "2", "8", "blue", "Blue", "Yellow"};
foreach (string colorString in colorStrings)
{
Colors colorValue;
if (Enum.TryParse(colorString, out colorValue))
Console.WriteLine(colorValue);
else
Console.WriteLine("{0} is not a member of the Colors enumeration.", colorString);
}
}
}
The code above generates the following result.