How to TryParse for Enum value?

c#, enums

Solution

As others have said, you have to implement your own `TryParse`. Simon Mourier is providing a full implementation which takes care of everything.

If you are using bitfield enums (i.e. flags), you also have to handle a string like `"MyEnum.Val1|MyEnum.Val2"` which is a combination of two enum values. If you just call `Enum.IsDefined` with this string, it will return false, even though `Enum.Parse` handles it correctly.

Update

As mentioned by Lisa and Christian in the comments, `Enum.TryParse` is now available for C# in .NET4 and up. MSDN Docs

Problem

I want to write a function which can validate a given value (passed as a string) against possible values of an `enum`. In the case of a match, it should return the enum instance; otherwise, it should return a default value. The function may not internally use `try`/`catch`, which excludes using `Enum.Parse`, which throws an exception when given an invalid argument. I'd like to use something along the lines of a `TryParse` function to implement this: ``` public static TEnum ToEnum<TEnum>(this string strEnumValue, TEnum defaultValue) { object enumValue; if (!TryParse (typeof (TEnum), strEnumValue, out enumValue)) { return defaultValue; } return (TEnum) enumValue; } ```

Original source

Related problems