c# parse string to enum code example

Example 1: string to enum c# 3

StatusEnum MyStatus = (StatusEnum) Enum.Parse(typeof(StatusEnum), "Active", true);

Example 2: string to enum c#

Enum.TryParse("Active", out StatusEnum myStatus);

Example 3: C#: casting string to enum object

public static T ToEnum<T>(this string value, T defaultValue) 
{
    if (string.IsNullOrEmpty(value))
    {
        return defaultValue;
    }

    T result;
    return Enum.TryParse<T>(value, true, out result) ? result : defaultValue;
}

Example 4: c# get enum value from string

//This example will parse a string to a Keys value
Keys key = (Keys)Enum.Parse(typeof(Keys), "Space");
//The key value will now be Keys.Space

Example 5: C#: casting string to enum object

public static TEnum ParseEnum<TEnum>(string value) where TEnum : struct
{
    TEnum tmp; 
    if (!Enum.TryParse<TEnum>(value, true, out tmp))
    {
        tmp = new TEnum();
    }
    return tmp;
}