Skip to content

Add a non-generic version of Enum.TryParse #14083

@yufeih

Description

@yufeih

These are the methods in Enum class related to string parsing.

public static object Parse(Type enumType, string value);
public static object Parse(Type enumType, string value, bool ignoreCase);

public static bool TryParse<TEnum>(string value, out TEnum result) 
where TEnum : struct;
public static bool TryParse<TEnum>(string value, bool ignoreCase, out TEnum result) 
where TEnum : struct;

Apparently Parse is exposed only in non-generic form, while TryParse is only exposed in generic form. This is somewhat inconsistent.

It is simple enough to call a non-generic method in a generic method, but not the other way around. So Parse can be made generic using the following helper. But it is a lot harder to wrap TryParse into TryParse(Type enumType) without reflection calls.

public static TEnum Parse<TEnum>(string value, bool ignoreCase)
{
    return Enum.Parse(typeof(TEnum), value, ignoreCase);
}

The suggestion is to add a non-generic Enum.TryParse method, the API signature would look like

public static bool TryParse(Type enumType, string value, out object result) 
public static bool TryParse(Type enumType, string value, bool ignoreCase, out object result) 

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions