.NET Framework Class Library
Enum..::.Parse Method (Type, String, Boolean)

Updated: May 2009

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.

Namespace:  System
Assembly:  mscorlib (in mscorlib.dll)
Syntax

Visual Basic (Declaration)
<ComVisibleAttribute(True)> _
Public Shared Function Parse ( _
    enumType As Type, _
    value As String, _
    ignoreCase As Boolean _
) As Object
Visual Basic (Usage)
Dim enumType As Type
Dim value As String
Dim ignoreCase As Boolean
Dim returnValue As Object

returnValue = Enum.Parse(enumType, _
    value, ignoreCase)
C#
[ComVisibleAttribute(true)]
public static Object Parse(
    Type enumType,
    string value,
    bool ignoreCase
)
Visual C++
[ComVisibleAttribute(true)]
public:
static Object^ Parse(
    Type^ enumType, 
    String^ value, 
    bool ignoreCase
)
JScript
public static function Parse(
    enumType : Type, 
    value : String, 
    ignoreCase : boolean
) : Object

Parameters

enumType
Type: System..::.Type
The Type of the enumeration.
value
Type: System..::.String
A string containing the name or value to convert.
ignoreCase
Type: System..::.Boolean
If true, ignore case; otherwise, regard case.

Return Value

Type: System..::.Object
An object of type enumType whose value is represented by value.
Exceptions

ExceptionCondition
ArgumentNullException

enumType or value is nullNothingnullptra null reference (Nothing in Visual Basic).

ArgumentException

enumType is not an Enum.

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

OverflowException

value is outside the range of the underlying type of enumType.

Remarks

The value 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 in value. If value is a list, the return value is the value of the specified names combined with a bitwise OR operation.

If value is a name that does not correspond to a named constant of enumType, the method throws an ArgumentException. If value is the string representation of an integer that does not represent an underlying value of the enumType 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 enumType. The following example defines a Colors enumeration, calls the Parse(Type, String, Boolean) 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.

Visual Basic
<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
         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 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.
C#
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.

The ignoreCase parameter specifies whether this operation is case-sensitive.

Examples

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

Visual Basic
Imports System

Public Class ParseTest

    <FlagsAttribute()> _
    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}", colorName, Convert.ToInt32([Enum].Parse(GetType(Colors), colorName)))
        Next colorName
        Console.WriteLine()
        Dim myOrange As Colors = CType([Enum].Parse(GetType(Colors), "Red, Yellow"), Colors)
        Console.WriteLine("The myOrange value {1} has the combined entries of {0}", myOrange, Convert.ToInt64(myOrange))
    End Sub
End Class

'This code example produces the following results:
'
'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
'
C#
using System;

public class ParseTest
{
    [FlagsAttribute]
    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}", colorName, 
                                         Convert.ToInt32(Enum.Parse(typeof(Colors), colorName)));
        }
        Console.WriteLine();
        Colors myOrange = (Colors)Enum.Parse(typeof(Colors), "Red, Yellow");
        Console.WriteLine("The myOrange value {1} has the combined entries of {0}", 
                           myOrange, Convert.ToInt64(myOrange));
    }
}

/*
This code example produces the following results:

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

*/
Visual C++
using namespace System;

[FlagsAttribute]
enum class Colors
{
   Red = 1,
   Green = 2,
   Blue = 4,
   Yellow = 8
};

int main()
{
   Console::WriteLine(  "The entries of the Colors enumeration are:" );
   Array^ a = Enum::GetNames( Colors::typeid );
   Int32 i = 0;
   while ( i < a->Length )
   {
      Object^ o = a->GetValue( i );
      Console::WriteLine( o->ToString() );
      i++;
   }

   Console::WriteLine();
   Object^ myOrange = Enum::Parse( Colors::typeid,  "Red, Yellow" );
   Console::WriteLine(  "The myOrange value has the combined entries of {0}", myOrange );
}

/*
This code example produces the following results:

The entries of the Colors Enum are:
Red
Green
Blue
Yellow

The myOrange value has the combined entries of Red, Yellow

*/
JScript
import System;

public class ParseTest {
    FlagsAttribute
    enum Colors { Red = 1, Green = 2, Blue = 4, Yellow = 8 };

    public static function Main() {
        Console.WriteLine("The entries of the Colors enumeration are:");
        for(var i : int in Enum.GetNames(Colors))
            Console.WriteLine(Enum.GetNames(Colors).GetValue(i));
        Console.WriteLine();
        var myOrange : Colors = Colors(Enum.Parse(Colors, "Red, Yellow"));
        Console.WriteLine("The myOrange value has the combined entries of {0}", myOrange);
    }
}

ParseTest.Main();

/*
This code example produces the following results:

The entries of the Colors Enum are:
Red
Green
Blue
Yellow

The myOrange value has the combined entries of Red, Yellow

*/
Platforms

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile for Smartphone, Windows Mobile for Pocket PC, Xbox 360, Zune

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Version Information

.NET Framework

Supported in: 3.5, 3.0, 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 3.5, 2.0

XNA Framework

Supported in: 3.0, 2.0, 1.0
See Also

Reference

Change History

Date

History

Reason

May 2009

Added OverflowException to the list of exceptions.

Content bug fix.

December 2008

Expanded the Remarks section and added an example.

Customer feedback.

Tags :


Community Content

Schammer
Multiple matches returns first result
If ignoreCase is true and value matches multiple names within an enumeration that differ only by case, the value that is defined earliest in the enumeration is returned.
Tags :

Page view tracker