C# Enum Parse(Type, String)
Description
Enum Parse(Type, String)
converts the string representation
of the name or numeric value of one or more enumerated constants to an equivalent
enumerated object.
Syntax
Enum.Parse(Type, String)
has the following syntax.
[ComVisibleAttribute(true)]/* w w w.j a v a 2 s . c o m*/
public static Object Parse(
Type enumType,
string value
)
Parameters
Enum.Parse(Type, String)
has the following parameters.
enumType
- An enumeration type.value
- A string containing the name or value to convert.
Returns
Enum.Parse(Type, String)
method returns An object of type enumType whose value is represented by value.
Example
using System;/*from w ww .jav a2 s. c om*/
[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)
{
try {
Colors colorValue = (Colors) Enum.Parse(typeof(Colors), colorString);
if (Enum.IsDefined(typeof(Colors), colorValue))
Console.WriteLine("Converted '{0}' to {1}.", colorString, colorValue.ToString());
else
Console.WriteLine(colorString);
}
catch (ArgumentException) {
Console.WriteLine("'{0}' is not a member of the Colors enumeration.", colorString);
}
}
}
}
The code above generates the following result.