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

How to Parse a String into an Enum in C#?

Susan Sarandon
Release: 2025-02-02 00:32:10
Original
730 people have browsed it

How to Parse a String into an Enum in C#?

In C#, the string is parsed as enumerated

When processing the HTML form and enumeration in C#, the string value may need to be converted to its corresponding enumeration value. Here are some methods to implement this task:

General parsing method (.NET CORE and .NET Framework 4.0)

In .NET CORE and .NET Framework 4.0 and higher versions, you could use a general parsing method:

<code class="language-csharp">bool statusSuccess = Enum.TryParse("Active", out StatusEnum myStatus);</code>
Copy after login
Simplified analysis method

If you cannot access the latest .NET version, you can create a simplified analysis routine:

<code class="language-csharp">public static T ParseEnum<T>(string value)
{
    return (T)Enum.Parse(typeof(T), value, true);
}

StatusEnum myStatus = EnumUtil.ParseEnum<StatusEnum>("Active");
// 或
StatusEnum myStatus = "Active".ToEnum<StatusEnum>();</code>
Copy after login
The method with the default value

If the string may not be an effective enumeration value, you can provide a default value in the parsing method:

<code class="language-csharp">public static T ToEnum<T>(this string value, T defaultValue)
{
    if (value == null || value == "")
        return defaultValue;

    T result;
    return Enum.TryParse<T>(value, true, out result) ? result : defaultValue;
}

StatusEnum myStatus = "Active".ToEnum(StatusEnum.None);</code>
Copy after login
Remember that when modifying core classes like string classes, use the expansion method carefully because it will affect all instances of this class, regardless of its context.

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

source:php.cn
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