How to get an Enum value from a string

Lets say you have an enum like this

public enum Colors 

And you need to get the enum value of ‘Colors.Red’, but you only have the string “red”.

I wrote this function to return the proper enum value and it doesn’t care if you pass in “red” or “RED” or “rEd” because it is case insensitive.

 private T GetEnumValue(string caseInsensitiveStringVal)
            var properName = Enum.GetNames(typeof(T)).SingleOrDefault(x => x.ToString().Equals(caseInsensitiveStringVal, StringComparison.OrdinalIgnoreCase));
            //get value from properName
            if (properName != null)
                return (T)Enum.Parse(typeof(T), properName);
            throw new InvalidDataException("Invalid value."); 


//Now call it like this
Colors myColor = GetEnumValue("rEd");

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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