Elegantly parsing C# Enums

Viewed 1039

Does anyone have a more elegant solution to parsing enums? The following just seems like a mess to me.

UserType userType = (UserType)Enum.Parse(typeof(UserType), iUserType.ToString());
4 Answers

Here is an extension method based on @vcsjones version and feedback, and from @Mones example:

public enum TestEnum
{
    None,
    A,
    B,
};

void Main()
{
    var testValues = new List<object>();
    testValues.AddRange(Enumerable.Range(-2, 6).Select(i => (object)i));
    testValues.AddRange(new List<string>() { String.Empty, "A", "B", "C", null });

    foreach (var testValue in testValues)
    {
        Console.WriteLine($"Testing value {testValue ?? String.Empty}:");
        TestEnum output;
        var enumValues = Enum.GetNames(typeof(TestEnum)).ToList();
        try
        {
            if (TestEnum.TryParse(testValue.ToString(), out output))
            {
                Console.WriteLine($"Succeeded with TryParse on {testValue} to {output}");
            }
            else
            {
                Console.WriteLine($"Failed to TryParse on {testValue}");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Test harness caught an exception: {ex.ToString()}");
        }

        var toEnumOutput = (testValue ?? String.Empty).ToString().Parse<TestEnum>();
        Console.WriteLine($"Parse<TEnum> returned {toEnumOutput}");

        Console.WriteLine();
        Console.WriteLine();
    }

}


public static class EnumExtensions
{
    public static TEnum Parse<TEnum>(this string value) where TEnum : struct
    {
        TEnum output = default(TEnum);
        var enumValues = Enum.GetNames(typeof(TEnum)).ToList();

        if (Enum.TryParse<TEnum>(value, true, out output))
            if (Enum.IsDefined(typeof(TEnum), value) || value.ToString().Contains(",") || enumValues.Contains(output.ToString()))
            {
                Console.WriteLine($"Converted '{value}' to {output}.");
                return output;
            }
            else
            {
                Console.WriteLine($"{value} is not an underlying value of the enumeration.");
            }
        else
        {
            Console.WriteLine($"{value} is not a member of the enumeration.");
        }
        return default(TEnum);
    }
}

The test harness gives this output:

Testing value -2:
Succeeded with TryParse on -2 to -2
-2 is not an underlying value of the enumeration.
Parse<TEnum> returned None


Testing value -1:
Succeeded with TryParse on -1 to -1
-1 is not an underlying value of the enumeration.
Parse<TEnum> returned None


Testing value 0:
Succeeded with TryParse on 0 to None
Converted '0' to None.
Parse<TEnum> returned None


Testing value 1:
Succeeded with TryParse on 1 to A
Converted '1' to A.
Parse<TEnum> returned A


Testing value 2:
Succeeded with TryParse on 2 to B
Converted '2' to B.
Parse<TEnum> returned B


Testing value 3:
Succeeded with TryParse on 3 to 3
3 is not an underlying value of the enumeration.
Parse<TEnum> returned None


Testing value :
Failed to TryParse on 
 is not a member of the enumeration.
Parse<TEnum> returned None


Testing value A:
Succeeded with TryParse on A to A
Converted 'A' to A.
Parse<TEnum> returned A


Testing value B:
Succeeded with TryParse on B to B
Converted 'B' to B.
Parse<TEnum> returned B


Testing value C:
Failed to TryParse on C
C is not a member of the enumeration.
Parse<TEnum> returned None


Testing value :
Test harness caught an exception: System.NullReferenceException: Object reference not set to an instance of an object.
   at UserQuery.Main() in C:\Users\Colin\AppData\Local\Temp\3\LINQPad5\_zhvrhwll\query_ludjga.cs:line 49
 is not a member of the enumeration.
Parse<TEnum> returned None

References:

Related