C# Enum TryParse(String, TEnum)
Description
Enum TryParse (String, TEnum)
converts
the string representation of the name or numeric value of one or more enumerated
constants to an equivalent enumerated object. The return value indicates
whether the conversion succeeded.
Syntax
Enum.TryParse(String, TEnum)
has the following syntax.
public static bool TryParse<TEnum>(
string value,/* w w w . j a v a 2 s .c om*/
out TEnum result
)
where TEnum : struct
Parameters
Enum.TryParse(String, TEnum)
has the following parameters.
TEnum
- The enumeration type to which to convert value.value
- The string representation of the enumeration name or underlying value to convert.result
- When this method returns, result contains an object of type TEnum whose value is represented by value if the parse operation succeeds. If the parse operation fails, result contains the default value of the underlying type of TEnum. Note that this value need not be a member of the TEnum enumeration. This parameter is passed uninitialized.
Returns
Enum.TryParse(String, TEnum)
method returns true if the value parameter was converted successfully; otherwise, false.
Example
The following example defines a Colors enumeration, calls the TryParse(String, TEnum) method to convert strings to their corresponding enumeration values.
/*w w w . j av a2s.c o 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.