Home > Backend Development > C++ > How to Convert a String to an Enum in C#?

How to Convert a String to an Enum in C#?

Mary-Kate Olsen
Release: 2025-02-02 00:41:18
Original
723 people have browsed it

How to Convert a String to an Enum in C#?

In the C#, the string is converted into enumeration

Pay an enumeration from the string

When processing the HTML Select tag with enumeration value, you need to convert the selected string value to the corresponding enumeration value. In C#, the preferred conversion method is

. Enum.TryParse

Enum.TryParse("Active", out StatusEnum myStatus);
Copy after login
For .NET CORE and .NET Framework 4.0, it required longer grammar:

StatusEnum myStatus = (StatusEnum)Enum.Parse(typeof(StatusEnum), "Active", true);
Copy after login
Customized enumeration analysis expansion method

For the sake of convenience, you can create a custom extension method to simplify the analysis process, such as:

public static T ParseEnum<T>(string value) => (T)Enum.Parse(typeof(T), value, true);
Copy after login
This extension method allows you to write:

StatusEnum myStatus = ParseEnum<StatusEnum>("Active");
Copy after login
Processing invalid enumeration value

In order to process the string value is not an effective enumeration value, you can add silent recognition to the

method: ParseEnum

public static T ToEnum<T>(string value, T defaultValue)
{
    if (string.IsNullOrEmpty(value)) return defaultValue;
    T result;
    return Enum.TryParse<T>(value, true, out result) ? result : defaultValue;
}
Copy after login
This allows you to use the following syntax:

The above is the detailed content of How to Convert a String to an Enum in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template