Enum.TryParse Method

Definition

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.

Overloads

TryParse(Type, ReadOnlySpan<Char>, Object)

Converts the span of characters representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.

TryParse(Type, String, Object)

Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.

TryParse(Type, ReadOnlySpan<Char>, Boolean, Object)

Converts the span of characters representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object. A parameter specifies whether the operation is case-insensitive.

TryParse(Type, String, Boolean, Object)

Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.

TryParse<TEnum>(ReadOnlySpan<Char>, TEnum)

Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.

TryParse<TEnum>(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.

TryParse<TEnum>(String, Boolean, TEnum)

Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object. A parameter specifies whether the operation is case-sensitive. The return value indicates whether the conversion succeeded.

TryParse<TEnum>(ReadOnlySpan<Char>, Boolean, TEnum)

Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object. A parameter specifies whether the operation is case-sensitive. The return value indicates whether the conversion succeeded.

TryParse(Type, ReadOnlySpan<Char>, Object)

Converts the span of characters representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.

public:
 static bool TryParse(Type ^ enumType, ReadOnlySpan<char> value, [Runtime::InteropServices::Out] System::Object ^ % result);
public static bool TryParse (Type enumType, ReadOnlySpan<char> value, out object? result);
static member TryParse : Type * ReadOnlySpan<char> * obj -> bool
Public Shared Function TryParse (enumType As Type, value As ReadOnlySpan(Of Char), ByRef result As Object) As Boolean

Parameters

enumType
Type

The enum type to use for parsing.

value
ReadOnlySpan<Char>

The span representation of the name or numeric value of one or more enumerated constants.

result
Object

When this method returns true, contains an enumeration constant that represents the parsed value.

Returns

true if the conversion succeeded; false otherwise.

Exceptions

.NET 8 and later versions: enumType is a Boolean-backed enumeration type.

Applies to

TryParse(Type, String, Object)

Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.

public:
 static bool TryParse(Type ^ enumType, System::String ^ value, [Runtime::InteropServices::Out] System::Object ^ % result);
public static bool TryParse (Type enumType, string? value, out object? result);
public static bool TryParse (Type enumType, string value, out object result);
static member TryParse : Type * string * obj -> bool
Public Shared Function TryParse (enumType As Type, value As String, ByRef result As Object) As Boolean

Parameters

enumType
Type

The enum type to use for parsing.

value
String

The string representation of the name or numeric value of one or more enumerated constants.

result
Object

When this method returns true, contains an enumeration constant that represents the parsed value.

Returns

true if the conversion succeeded; false otherwise.

Exceptions

.NET 8 and later versions: enumType is a Boolean-backed enumeration type.

Applies to

TryParse(Type, ReadOnlySpan<Char>, Boolean, Object)

Converts the span of characters representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object. A parameter specifies whether the operation is case-insensitive.

public:
 static bool TryParse(Type ^ enumType, ReadOnlySpan<char> value, bool ignoreCase, [Runtime::InteropServices::Out] System::Object ^ % result);
public static bool TryParse (Type enumType, ReadOnlySpan<char> value, bool ignoreCase, out object? result);
static member TryParse : Type * ReadOnlySpan<char> * bool * obj -> bool
Public Shared Function TryParse (enumType As Type, value As ReadOnlySpan(Of Char), ignoreCase As Boolean, ByRef result As Object) As Boolean

Parameters

enumType
Type

The enum type to use for parsing.

value
ReadOnlySpan<Char>

The span representation of the name or numeric value of one or more enumerated constants.

ignoreCase
Boolean

true to read enumType in case insensitive mode; false to read enumType in case sensitive mode.

result
Object

When this method returns true, contains an enumeration constant that represents the parsed value.

Returns

true if the conversion succeeded; false otherwise.

Exceptions

.NET 8 and later versions: enumType is a Boolean-backed enumeration type.

Applies to

TryParse(Type, String, Boolean, Object)

Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.

public:
 static bool TryParse(Type ^ enumType, System::String ^ value, bool ignoreCase, [Runtime::InteropServices::Out] System::Object ^ % result);
public static bool TryParse (Type enumType, string? value, bool ignoreCase, out object? result);
public static bool TryParse (Type enumType, string value, bool ignoreCase, out object result);
static member TryParse : Type * string * bool * obj -> bool
Public Shared Function TryParse (enumType As Type, value As String, ignoreCase As Boolean, ByRef result As Object) As Boolean

Parameters

enumType
Type

The enum type to use for parsing.

value
String

The string representation of the name or numeric value of one or more enumerated constants.

ignoreCase
Boolean

true to read value in case insensitive mode; false to read value in case sensitive mode.

result
Object

When this method returns true, contains an enumeration constant that represents the parsed value.

Returns

true if the conversion succeeded; false otherwise.

Exceptions

.NET 8 and later versions: enumType is a Boolean-backed enumeration type.

Applies to

TryParse<TEnum>(ReadOnlySpan<Char>, TEnum)

Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.

public:
generic <typename TEnum>
 where TEnum : value class static bool TryParse(ReadOnlySpan<char> value, [Runtime::InteropServices::Out] TEnum % result);
public static bool TryParse<TEnum> (ReadOnlySpan<char> value, out TEnum result) where TEnum : struct;
static member TryParse : ReadOnlySpan<char> * 'Enum -> bool (requires 'Enum : struct)
Public Shared Function TryParse(Of TEnum As Structure) (value As ReadOnlySpan(Of Char), ByRef result As TEnum) As Boolean

Type Parameters

TEnum

The type of the result object.

Parameters

value
ReadOnlySpan<Char>

The span representation of the name or numeric value of one or more enumerated constants.

result
TEnum

When this method returns true, contains an enumeration constant that represents the parsed value.

Returns

true if the conversion succeeded; false otherwise.

Exceptions

TEnum is not an enumeration type.

.NET 8 and later versions: TEnum is a Boolean-backed enumeration type.

Applies to

TryParse<TEnum>(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.

public:
generic <typename TEnum>
 where TEnum : value class static bool TryParse(System::String ^ value, [Runtime::InteropServices::Out] TEnum % result);
public static bool TryParse<TEnum> (string value, out TEnum result) where TEnum : struct;
public static bool TryParse<TEnum> (string? value, out TEnum result) where TEnum : struct;
static member TryParse : string * 'Enum -> bool (requires 'Enum : struct)
Public Shared Function TryParse(Of TEnum As Structure) (value As String, ByRef result As TEnum) As Boolean

Type Parameters

TEnum

The enumeration type to which to convert value.

Parameters

value
String

The case-sensitive string representation of the enumeration name or underlying value to convert.

result
TEnum

When this method returns, contains an object of type TEnum whose value is represented by value if the parse operation succeeds. If the parse operation fails, contains the default value of the underlying type of TEnum. This parameter is passed uninitialized.

Returns

true if the value parameter was converted successfully; otherwise, false.

Exceptions

TEnum is not an enumeration type.

.NET 8 and later versions: TEnum is a Boolean-backed enumeration type.

Examples

The following example defines a Colors enumeration, calls the TryParse<TEnum>(String, TEnum) method to convert strings to their corresponding enumeration values, and calls the IsDefined method to ensure that particular integral values are underlying values in the Colors enumeration.

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", "Red, Green" };
      foreach (string colorString in colorStrings)
      {
         Colors colorValue;
         if (Enum.TryParse(colorString, out colorValue))
            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);
         else
            Console.WriteLine("{0} is not a member of the Colors enumeration.", colorString);
      }
   }
}
// The example displays the following output:
//       Converted '0' to None.
//       Converted '2' to Green.
//       8 is not an underlying value of the Colors enumeration.
//       blue is not a member of the Colors enumeration.
//       Converted 'Blue' to Blue.
//       Yellow is not a member of the Colors enumeration.
//       Converted 'Red, Green' to Red, Green.
open System

[<Flags>]
type Colors =
    | None = 0
    | Red = 1
    | Green = 2
    | Blue = 4

let colorStrings = 
    [ "0"; "2"; "8"; "blue"; "Blue"; "Yellow"; "Red, Green" ]
for colorString in colorStrings do
    match Enum.TryParse colorString with
    | true, colorValue ->
        if Enum.IsDefined(typeof<Colors>, colorValue) || (string colorValue).Contains "," then
            printfn $"Converted '{colorString}' to {colorValue}."
        else
            printfn $"{colorString} is not an underlying value of the Colors enumeration."
    | _ ->
        printfn $"{colorString} is not a member of the Colors enumeration."
// The example displays the following output:
//       Converted '0' to None.
//       Converted '2' to Green.
//       8 is not an underlying value of the Colors enumeration.
//       blue is not a member of the Colors enumeration.
//       Converted 'Blue' to Blue.
//       Yellow is not a member of the Colors enumeration.
//       Converted 'Red, Green' to Red, Green.
<Flags> Enum Colors As Integer
   None = 0
   Red = 1
   Green = 2
   Blue = 4
End Enum

Module Example
   Public Sub Main()
      Dim colorStrings() As String = {"0", "2", "8", "blue", "Blue", "Yellow", "Red, Green"}
      For Each colorString As String In colorStrings
         Dim colorValue As Colors
         If [Enum].TryParse(colorString, colorValue) Then        
            If [Enum].IsDefined(GetType(Colors), colorValue) Or colorValue.ToString().Contains(",") Then 
               Console.WriteLine("Converted '{0}' to {1}.", colorString, colorValue.ToString())
            Else
               Console.WriteLine("{0} is not an underlying value of the Colors enumeration.", colorString)            
            End If                    
         Else
            Console.WriteLine("{0} is not a member of the Colors enumeration.", colorString)
         End If
      Next
   End Sub
End Module
' The example displays the following output:
'    Converted '0' to None.
'    Converted '2' to Green.
'    8 is not an underlying value of the Colors enumeration.
'    blue is not a member of the Colors enumeration.
'    Converted 'Blue' to Blue.
'    Yellow is not a member of the Colors enumeration.
'    Converted 'Red, Green' to Red, Green.

Remarks

TryParse<TEnum>(String, TEnum) is identical to the Parse(Type, String) method, except that instead of throwing an exception, it returns false if the conversion fails. It eliminates the need for exception handling when parsing the string representation of an enumeration value.

The value parameter contains the string representation of an enumeration member's underlying value or named constant, or a list of named constants or underlying values delimited by commas (,). If value includes multiple named constants or values, one or more blank spaces can precede or follow each value, name, or comma in value. If value is a list, result reflects the value of the specified names or underlying values combined with a bitwise OR operation. If value is the string representation of the name of an enumeration value, the comparison of value with enumeration names is case-sensitive.

If value is a name that does not correspond to a named constant of TEnum, the method returns false. If value is the string representation of an integer that does not represent an underlying value of the TEnum enumeration, the method returns an enumeration member whose underlying value is value converted to an integral type. If this behavior is undesirable, call the IsDefined method to ensure that a particular string representation of an integer is actually a member of TEnum.

If the parse operation fails, the result parameter contains the default value of 0, which may not be a member of the underlying TEnum enumeration. If no values are assigned to the named constants in TEnum, the default is equal to the first member of the TEnum. Otherwise, the default is equal to the member in the enumeration with an assigned value of 0.

See also

Applies to

TryParse<TEnum>(String, Boolean, TEnum)

Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object. A parameter specifies whether the operation is case-sensitive. The return value indicates whether the conversion succeeded.

public:
generic <typename TEnum>
 where TEnum : value class static bool TryParse(System::String ^ value, bool ignoreCase, [Runtime::InteropServices::Out] TEnum % result);
public static bool TryParse<TEnum> (string value, bool ignoreCase, out TEnum result) where TEnum : struct;
public static bool TryParse<TEnum> (string? value, bool ignoreCase, out TEnum result) where TEnum : struct;
static member TryParse : string * bool * 'Enum -> bool (requires 'Enum : struct)
Public Shared Function TryParse(Of TEnum As Structure) (value As String, ignoreCase As Boolean, ByRef result As TEnum) As Boolean

Type Parameters

TEnum

The enumeration type to which to convert value.

Parameters

value
String

The string representation of the enumeration name or underlying value to convert.

ignoreCase
Boolean

true to ignore case; false to consider case.

result
TEnum

When this method returns, contains an object of type TEnum whose value is represented by value if the parse operation succeeds. If the parse operation fails, contains the default value of the underlying type of TEnum. This parameter is passed uninitialized.

Returns

true if the value parameter was converted successfully; otherwise, false.

Exceptions

TEnum is not an enumeration type.

.NET 8 and later versions: TEnum is a Boolean-backed enumeration type.

Examples

The following example defines a Colors enumeration, calls the TryParse<TEnum>(String, Boolean, TEnum) method to convert strings to their corresponding enumeration values, and calls the IsDefined method to ensure that particular integral values are underlying values in the Colors enumeration. The TryParse<TEnum>(String, Boolean, TEnum) method uses case-insensitive comparison when trying to convert the string representations of named constants to their equivalent enumeration values.

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", "Red, Green" };
      foreach (string colorString in colorStrings)
      {
         Colors colorValue;
         if (Enum.TryParse(colorString, true, out colorValue))
            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);
         else
            Console.WriteLine("{0} is not a member of the Colors enumeration.", colorString);
      }
   }
}
// The example displays the following output:
//       Converted '0' to None.
//       Converted '2' to Green.
//       8 is not an underlying value of the Colors enumeration.
//       Converted 'blue' to Blue.
//       Converted 'Blue' to Blue.
//       Yellow is not a member of the Colors enumeration.
//       Converted 'Red, Green' to Red, Green.
open System

[<Flags>]
type Colors =
    | None = 0
    | Red = 1
    | Green = 2
    | Blue = 4

let colorStrings = 
    [ "0"; "2"; "8"; "blue"; "Blue"; "Yellow"; "Red, Green" ]
for colorString in colorStrings do
    match Enum.TryParse(colorString, true) with
    | true, colorValue ->
        if Enum.IsDefined(typeof<Colors>, colorValue) || (string colorValue).Contains "," then
            printfn $"Converted '{colorString}' to {colorValue}."
        else
            printfn $"{colorString} is not an underlying value of the Colors enumeration."
    | _ ->
        printfn $"{colorString} is not a member of the Colors enumeration."
// The example displays the following output:
//       Converted '0' to None.
//       Converted '2' to Green.
//       8 is not an underlying value of the Colors enumeration.
//       Converted 'blue' to Blue.
//       Converted 'Blue' to Blue.
//       Yellow is not a member of the Colors enumeration.
//       Converted 'Red, Green' to Red, Green.
<Flags> Enum Colors As Integer
   None = 0
   Red = 1
   Green = 2
   Blue = 4
End Enum

Module Example
   Public Sub Main()
      Dim colorStrings() As String = {"0", "2", "8", "blue", "Blue", "Yellow", "Red, Green"}
      For Each colorString As String In colorStrings
         Dim colorValue As Colors
         If [Enum].TryParse(colorString, True, colorValue) Then        
            If [Enum].IsDefined(GetType(Colors), colorValue) Or colorValue.ToString().Contains(",") Then 
               Console.WriteLine("Converted '{0}' to {1}.", colorString, colorValue.ToString())
            Else
               Console.WriteLine("{0} is not an underlying value of the Colors enumeration.", colorString)            
            End If                    
         Else
            Console.WriteLine("{0} is not a member of the Colors enumeration.", colorString)
         End If
      Next
   End Sub
End Module
' The example displays the following output:
'       Converted '0' to None.
'       Converted '2' to Green.
'       8 is not an underlying value of the Colors enumeration.
'       Converted 'blue' to Blue.
'       Converted 'Blue' to Blue.
'       Yellow is not a member of the Colors enumeration.
'       Converted 'Red, Green' to Red, Green.

Remarks

TryParse<TEnum>(String, Boolean, TEnum) is identical to the Parse(Type, String, Boolean) method, except that instead of throwing an exception, it returns false if the conversion fails. It eliminates the need for exception handling when parsing the string representation of an enumeration value.

The value parameter contains the string representation of an enumeration member's underlying value or named constant, or a list of named constants or underlying values delimited by commas (,). If value includes multiple named constants or values, one or more blank spaces can precede or follow each value, name, or comma in value. If value is a list, result reflects the value of the specified names or underlying values combined with a bitwise OR operation. If value is the string representation of the name of an enumeration value, the comparison of value with enumeration names depends on the ignoreCase parameter. If true, the comparison is case-insensitive; if false, it is case-sensitive.

If value is a name that does not correspond to a named constant of TEnum, the method returns false. If value is the string representation of an integer that does not represent an underlying value of the TEnum enumeration, the method returns an enumeration member whose underlying value is value converted to an integral type. If this behavior is undesirable, call the IsDefined method to ensure that a particular string representation of an integer is actually a member of TEnum.

If the parse operation fails, the result parameter contains the default value of 0, which may not be a member of the underlying TEnum enumeration. If no values are assigned to the named constants in TEnum, the default is equal to the first member of the TEnum. Otherwise, the default is equal to the member in the enumeration with an assigned value of 0.

See also

Applies to

TryParse<TEnum>(ReadOnlySpan<Char>, Boolean, TEnum)

Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object. A parameter specifies whether the operation is case-sensitive. The return value indicates whether the conversion succeeded.

public:
generic <typename TEnum>
 where TEnum : value class static bool TryParse(ReadOnlySpan<char> value, bool ignoreCase, [Runtime::InteropServices::Out] TEnum % result);
public static bool TryParse<TEnum> (ReadOnlySpan<char> value, bool ignoreCase, out TEnum result) where TEnum : struct;
static member TryParse : ReadOnlySpan<char> * bool * 'Enum -> bool (requires 'Enum : struct)
Public Shared Function TryParse(Of TEnum As Structure) (value As ReadOnlySpan(Of Char), ignoreCase As Boolean, ByRef result As TEnum) As Boolean

Type Parameters

TEnum

The type of the result object.

Parameters

value
ReadOnlySpan<Char>

The span representation of the name or numeric value of one or more enumerated constants.

ignoreCase
Boolean

true to ignore case; false to consider case.

result
TEnum

When this method returns true, contains an enumeration constant that represents the parsed value.

Returns

true if the conversion succeeded; false otherwise.

Exceptions

TEnum is not an enumeration type.

.NET 8 and later versions: TEnum is a Boolean-backed enumeration type.

Applies to