0

I used a generic method to parse all these enum types, but there is an error, I am not sure how to fix it. Could someone have a great idea? Thanks

public static T TryParseEnum<T>(string value)
{
    T t;
    bool ok = Enum.TryParse<T>(value, out t);
    return t;
}

Error:

The type 'T' must be a non-nullable value type in order to use it as parameter 'TEnum' in the generic type or method 'Enum.TryParse(string, out TEnum)'

Update: Thanks yours help, and I have fixed it a new method.

public static T TryParseEnum<T>(string value) where T : struct
{
    T t = default(T);
    bool ok = Enum.TryParse<T>(value, out t);
    return t;
}
Bes Ley
  • 1,685
  • 1
  • 20
  • 39
  • there is already a TryParse i guess in `Enum` type in BCL – Ehsan Sajjad Jan 05 '19 at 14:13
  • 1
    FYI, in C# 7.3, there's a new `Enum` generic constraint: https://blogs.msdn.microsoft.com/seteplia/2018/06/12/dissecting-new-generics-constraints-in-c-7-3/ – ESG Jan 05 '19 at 14:41

0 Answers0