Parse string or int or enum to enum, specifies whether the operation is case-insensitive in CSharp
Description
The following code shows how to parse string or int or enum to enum, specifies whether the operation is case-insensitive.
Example
using System;// w w w. j ava 2 s.co m
[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", "Red, Green" };
foreach (string colorString in colorStrings)
{
Colors colorValue = (Colors)Enum.Parse(typeof(Colors), colorString, true);
if (Enum.IsDefined(typeof(Colors), colorValue) | colorValue.ToString().Contains(","))
Console.WriteLine("Converted '{0}' to {1}.", colorString, colorValue.ToString());
else
Console.WriteLine("{0} is not an underlying value of the Colors enumeration.", colorString);
}
}
}
The code above generates the following result.