Create enum instance from a string in CSharp

Description

The following code shows how to create enum instance from a string.

Example


using System;//from   www  . ja  v a  2s.  c  o m

enum Color
{
    red,
    green,
    yellow
}

public class MainClass
{
    public static void Main()
    {
        Color c = Color.red;
        
        // enum value from a string, ignore case
        c = (Color) Enum.Parse(typeof(Color), "Red", true);
        Console.WriteLine("string value is: {0}", c);
        
    }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    Data Types »




C# Data Types
Bool
Byte
Char
Decimal
Double
Float
Integer
Long
Short
String
C# Array
Array Example
Byte Array
C# Standard Data Type Format
BigInteger
Complex
Currency
DateTime
DateTimeOffset
DateTime Format Parse Convert
TimeSpan
TimeZone
Enum
Null
tuple
var