Movatterモバイル変換


[0]ホーム

URL:


Skip to main contentSkip to in-page navigation

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Download Microsoft EdgeMore info about Internet Explorer and Microsoft Edge
Table of contentsExit editor mode

Enum.Parse Method

Definition

Namespace:
System
Assemblies:
netstandard.dll, System.Runtime.dll
Assemblies:
mscorlib.dll, System.Runtime.dll
Assembly:
System.Runtime.dll
Assembly:
mscorlib.dll
Assembly:
netstandard.dll

Important

Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.

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

Overloads

NameDescription
Parse(Type, ReadOnlySpan<Char>)

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

Parse(Type, String)

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

Parse(Type, ReadOnlySpan<Char>, Boolean)

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.

Parse(Type, String, Boolean)

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-insensitive.

Parse<TEnum>(String, Boolean)

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

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

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

Parse<TEnum>(ReadOnlySpan<Char>)

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

Parse<TEnum>(String)

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

Parse(Type, ReadOnlySpan<Char>)

Source:
Enum.cs
Source:
Enum.cs
Source:
Enum.cs
Source:
Enum.cs

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 System::Object ^ Parse(Type ^ enumType, ReadOnlySpan<char> value);
public static object Parse(Type enumType, ReadOnlySpan<char> value);
static member Parse : Type * ReadOnlySpan<char> -> obj
Public Shared Function Parse (enumType As Type, value As ReadOnlySpan(Of Char)) As Object

Parameters

enumType
Type

An enumeration type.

value
ReadOnlySpan<Char>

A span containing the name or value to convert.

Returns

An object of typeenumType whose value is represented byvalue.

Exceptions

enumType isnull.

enumType is not anEnum.

value is either an empty string or only contains white space.

value is a name, but not one of the named constants defined for the enumeration.

value is outside the range of the underlying type ofenumType.

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

Applies to

Parse(Type, String)

Source:
Enum.cs
Source:
Enum.cs
Source:
Enum.cs
Source:
Enum.cs

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

public: static System::Object ^ Parse(Type ^ enumType, System::String ^ value);
public static object Parse(Type enumType, string value);
[System.Runtime.InteropServices.ComVisible(true)]public static object Parse(Type enumType, string value);
static member Parse : Type * string -> obj
[<System.Runtime.InteropServices.ComVisible(true)>]static member Parse : Type * string -> obj
Public Shared Function Parse (enumType As Type, value As String) As Object

Parameters

enumType
Type

An enumeration type.

value
String

A string containing the name or value to convert.

Returns

An object of typeenumType whose value is represented byvalue.

Attributes

Exceptions

enumType orvalue isnull.

enumType is not anEnum.

-or-

value is either an empty string or only contains white space.

-or-

value is a name, but not one of the named constants defined for the enumeration.

value is outside the range of the underlying type ofenumType.

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

Examples

The following example uses theParse(Type, String) method to parse an array of strings that are created by calling theGetNames method. It also uses theParse(Type, String) method to parse an enumeration value that consists of a bit field.

using System;public class ParseTest{    [Flags]    enum Colors { Red = 1, Green = 2, Blue = 4, Yellow = 8 };    public static void Main()    {        Console.WriteLine("The entries of the Colors enumeration are:");        foreach (string colorName in Enum.GetNames(typeof(Colors)))        {            Console.WriteLine("{0} = {1:D}", colorName,                                         Enum.Parse(typeof(Colors), colorName));        }        Console.WriteLine();        Colors orange = (Colors) Enum.Parse(typeof(Colors), "Red, Yellow");        Console.WriteLine("The orange value {0:D} has the combined entries of {0}",                           orange);    }}/*This code example produces the following results:The entries of the Colors Enum are:Red = 1Green = 2Blue = 4Yellow = 8The orange value 9 has the combined entries of Red, Yellow*/
open System[<Flags>]type Colors =    | Red = 1    | Green = 2    | Blue = 4    | Yellow = 8printfn "The entries of the Colors enumeration are:"for colorName in Enum.GetNames typeof<Colors> do    printfn $"{colorName} = {Enum.Parse(typeof<Colors>, colorName):D}"printfn ""let orange = Enum.Parse(typeof<Colors>, "Red, Yellow") :?> Colorsprintfn $"The orange value {orange:D} has the combined entries of {orange}"// This code example produces the following results://     The entries of the Colors Enum are://     Red = 1//     Green = 2//     Blue = 4//     Yellow = 8//    //     The orange value 9 has the combined entries of Red, Yellow
Public Class ParseTest    <Flags()> _    Enum Colors        Red = 1        Green = 2        Blue = 4        Yellow = 8    End Enum    Public Shared Sub Main()        Console.WriteLine("The entries of the Colors enumeration are:")        Dim colorName As String        For Each colorName In [Enum].GetNames(GetType(Colors))            Console.WriteLine("{0} = {1:D}", colorName, [Enum].Parse(GetType(Colors), colorName))        Next        Console.WriteLine()        Dim orange As Colors = CType([Enum].Parse(GetType(Colors), "Red, Yellow"), Colors)        Console.WriteLine("The orange value {0:D} has the combined entries of {0}", orange)    End SubEnd Class'This example displays the following output:''The entries of the Colors Enum are:'Red = 1'Green = 2'Blue = 4'Yellow = 8''The myOrange value 9 has the combined entries of Red, Yellow'

Remarks

Thevalue parameter contains the string representation of an enumeration member's underlying value or named constant, or a list of named constants delimited by commas (,). One or more blank spaces can precede or follow each value, name, or comma invalue. Ifvalue is a list, the return value is the value of the specified names combined with a bitwiseOR operation.

Ifvalue is a name that does not correspond to a named constant ofenumType, the method throws anArgumentException. Ifvalue is the string representation of an integer that does not represent an underlying value of theenumType enumeration, the method returns an enumeration member whose underlying value isvalue converted to an integral type. If this behavior is undesirable, call theIsDefined method to ensure that a particular string representation of an integer is actually a member ofenumType. The following example defines aColors enumeration, calls theParse(Type, String) method to convert strings to their corresponding enumeration values, and calls theIsDefined method to ensure that particular integral values are underlying values in theColors 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)      {         try {            Colors colorValue = (Colors) Enum.Parse(typeof(Colors), colorString);            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);         }         catch (ArgumentException) {            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 = 4let colorStrings = [ "0"; "2"; "8"; "blue"; "Blue"; "Yellow"; "Red, Green" ]for colorString in colorStrings do    try        let colorValue = Enum.Parse(typeof<Colors>, colorString) :?> Colors        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."    with :? ArgumentException ->        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 = 4End EnumModule Example   Public Sub Main()      Dim colorStrings() As String = {"0", "2", "8", "blue", "Blue", "Yellow", "Red, Green"}      For Each colorString As String In colorStrings         Try            Dim colorValue As Colors = CType([Enum].Parse(GetType(Colors), colorString), Colors)                    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                             Catch e As ArgumentException            Console.WriteLine("'{0}' is not a member of the Colors enumeration.", colorString)         End Try      Next   End SubEnd 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.

This operation is case-sensitive.

See also

Applies to

Parse(Type, ReadOnlySpan<Char>, Boolean)

Source:
Enum.cs
Source:
Enum.cs
Source:
Enum.cs
Source:
Enum.cs

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 System::Object ^ Parse(Type ^ enumType, ReadOnlySpan<char> value, bool ignoreCase);
public static object Parse(Type enumType, ReadOnlySpan<char> value, bool ignoreCase);
static member Parse : Type * ReadOnlySpan<char> * bool -> obj
Public Shared Function Parse (enumType As Type, value As ReadOnlySpan(Of Char), ignoreCase As Boolean) As Object

Parameters

enumType
Type

An enumeration type.

value
ReadOnlySpan<Char>

A span containing the name or value to convert.

ignoreCase
Boolean

true to ignore case;false to regard case.

Returns

An object of typeenumType whose value is represented byvalue.

Exceptions

enumType isnull.

enumType is not anEnum.

value is either an empty string or only contains white space.

value is a name, but not one of the named constants defined for the enumeration.

value is outside the range of the underlying type ofenumType

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

Applies to

Parse(Type, String, Boolean)

Source:
Enum.cs
Source:
Enum.cs
Source:
Enum.cs
Source:
Enum.cs

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-insensitive.

public: static System::Object ^ Parse(Type ^ enumType, System::String ^ value, bool ignoreCase);
public static object Parse(Type enumType, string value, bool ignoreCase);
[System.Runtime.InteropServices.ComVisible(true)]public static object Parse(Type enumType, string value, bool ignoreCase);
static member Parse : Type * string * bool -> obj
[<System.Runtime.InteropServices.ComVisible(true)>]static member Parse : Type * string * bool -> obj
Public Shared Function Parse (enumType As Type, value As String, ignoreCase As Boolean) As Object

Parameters

enumType
Type

An enumeration type.

value
String

A string containing the name or value to convert.

ignoreCase
Boolean

true to ignore case;false to regard case.

Returns

An object of typeenumType whose value is represented byvalue.

Attributes

Exceptions

enumType orvalue isnull.

enumType is not anEnum.

-or-

value is either an empty string ("") or only contains white space.

-or-

value is a name, but not one of the named constants defined for the enumeration.

value is outside the range of the underlying type ofenumType.

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

Examples

The following example uses theParse(Type, String, Boolean) method to parse an array of strings that are created by calling theGetNames method. It also uses theParse(Type, String) method to parse an enumeration value that consists of a bit field.

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)      {         try {            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);         }         catch (ArgumentException) {            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 = 4let colorStrings = [ "0"; "2"; "8"; "blue"; "Blue"; "Yellow"; "Red, Green" ]for colorString in colorStrings do    try        let colorValue = Enum.Parse(typeof<Colors>, colorString, true) :?> Colors        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."    with :? ArgumentException ->        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 = 4End EnumModule Example   Public Sub Main()      Dim colorStrings() As String = {"0", "2", "8", "blue", "Blue", "Yellow", "Red, Green"}      For Each colorString As String In colorStrings         Try            Dim colorValue As Colors = CType([Enum].Parse(GetType(Colors), colorString, True), Colors)                    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                             Catch e As ArgumentException            Console.WriteLine("{0} is not a member of the Colors enumeration.", colorString)         End Try      Next   End SubEnd 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

Thevalue parameter contains the string representation of an enumeration member's underlying value or named constant, or a list of named constants delimited by commas (,). One or more blank spaces can precede or follow each value, name, or comma invalue. Ifvalue is a list, the return value is the value of the specified names combined with a bitwiseOR operation.

Ifvalue is a name that does not correspond to a named constant ofenumType, the method throws anArgumentException. Ifvalue is the string representation of an integer that does not represent an underlying value of theenumType enumeration, the method returns an enumeration member whose underlying value isvalue converted to an integral type. If this behavior is undesirable, call theIsDefined method to ensure that a particular string representation of an integer is actually a member ofenumType. The following example defines aColors enumeration, calls theParse(Type, String, Boolean) method to convert strings to their corresponding enumeration values, and calls theIsDefined method to ensure that particular integral values are underlying values in theColors enumeration.

TheignoreCase parameter specifies whether this operation is case-sensitive.

See also

Applies to

Parse<TEnum>(String, Boolean)

Source:
Enum.cs
Source:
Enum.cs
Source:
Enum.cs
Source:
Enum.cs

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

public:generic <typename TEnum> where TEnum : value class static TEnum Parse(System::String ^ value, bool ignoreCase);
public static TEnum Parse<TEnum>(string value, bool ignoreCase) where TEnum : struct;
static member Parse : string * bool -> 'Enum (requires 'Enum : struct)
Public Shared Function Parse(Of TEnum As Structure) (value As String, ignoreCase As Boolean) As TEnum

Type Parameters

TEnum

An enumeration type.

Parameters

value
String

A string containing the name or value to convert.

ignoreCase
Boolean

true to ignore case;false to regard case.

Returns

TEnum

An object of typeTEnum whose value is represented byvalue.

Exceptions

TEnum is not anEnum type.

value does not contain enumeration information.

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

Applies to

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

Source:
Enum.cs
Source:
Enum.cs
Source:
Enum.cs
Source:
Enum.cs

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

public:generic <typename TEnum> where TEnum : value class static TEnum Parse(ReadOnlySpan<char> value, bool ignoreCase);
public static TEnum Parse<TEnum>(ReadOnlySpan<char> value, bool ignoreCase) where TEnum : struct;
static member Parse : ReadOnlySpan<char> * bool -> 'Enum (requires 'Enum : struct)
Public Shared Function Parse(Of TEnum As Structure) (value As ReadOnlySpan(Of Char), ignoreCase As Boolean) As TEnum

Type Parameters

TEnum

An enumeration type.

Parameters

value
ReadOnlySpan<Char>

A span containing the name or value to convert.

ignoreCase
Boolean

true to ignore case;false to regard case.

Returns

TEnum

TEnum An object of typeTEnum whose value is represented byvalue.

Exceptions

TEnum is not anEnum type.

value does not contain enumeration information.

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

Applies to

Parse<TEnum>(ReadOnlySpan<Char>)

Source:
Enum.cs
Source:
Enum.cs
Source:
Enum.cs
Source:
Enum.cs

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

public:generic <typename TEnum> where TEnum : value class static TEnum Parse(ReadOnlySpan<char> value);
public static TEnum Parse<TEnum>(ReadOnlySpan<char> value) where TEnum : struct;
static member Parse : ReadOnlySpan<char> -> 'Enum (requires 'Enum : struct)
Public Shared Function Parse(Of TEnum As Structure) (value As ReadOnlySpan(Of Char)) As TEnum

Type Parameters

TEnum

An enumeration type.

Parameters

value
ReadOnlySpan<Char>

A span containing the name or value to convert.

Returns

TEnum

TEnum An object of typeTEnum whose value is represented byvalue.

Exceptions

TEnum is not anEnum type.

value does not contain enumeration information.

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

Applies to

Parse<TEnum>(String)

Source:
Enum.cs
Source:
Enum.cs
Source:
Enum.cs
Source:
Enum.cs

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

public:generic <typename TEnum> where TEnum : value class static TEnum Parse(System::String ^ value);
public static TEnum Parse<TEnum>(string value) where TEnum : struct;
static member Parse : string -> 'Enum (requires 'Enum : struct)
Public Shared Function Parse(Of TEnum As Structure) (value As String) As TEnum

Type Parameters

TEnum

An enumeration type.

Parameters

value
String

A string containing the name or value to convert.

Returns

TEnum

An object of typeTEnum whose value is represented byvalue.

Exceptions

TEnum is not anEnum type.

value does not contain enumeration information.

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

Applies to

Collaborate with us on GitHub
The source for this content can be found on GitHub, where you can also create and review issues and pull requests. For more information, seeour contributor guide.

Feedback

Was this page helpful?

YesNoNo

Need help with this topic?

Want to try using Ask Learn to clarify or guide you through this topic?

Suggest a fix?

In this article

Was this page helpful?

YesNo
NoNeed help with this topic?

Want to try using Ask Learn to clarify or guide you through this topic?

Suggest a fix?