ILT – How to convert string to enum in C#

15-08-2012

How to convert a value to an enum?

How to find the matching enum value?

Convert object to enum?

How to use Enum.Parse method?

Solution:
Use the Enum.Parse method as shown below to convert your value to the appropriate enumerator type.

Enum declaration – for explanation

// enum declaration - for explanation

    public enum UNIT
    {
        g, kg, ml,L,m,cm
    }

Actual casting

// Create a String Variable

String stringValue = "cm";

// Get the matching enum type value

UNIT myUnit = (UNIT)Enum.Parse(typeof(UNIT), stringValue);

Menol
ILT

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: