Home >Backend Development >C++ >How Can I Get the String Representation of an Enum in C# More Elegantly?

How Can I Get the String Representation of an Enum in C# More Elegantly?

Susan Sarandon
Susan SarandonOriginal
2025-01-29 07:57:09320browse

How Can I Get the String Representation of an Enum in C# More Elegantly?

Get the string of C#enumerated elegantly

Consider the following enumeration:

To get string values ​​(such as "Forms" instead of ID 1), a solution is required. Although the existing attribute -based methods and dictionary methods provides a transformation solution, there are more elegant solutions.
<code class="language-csharp">public enum AuthenticationMethod
{
    FORMS = 1,
    WINDOWSAUTHENTICATION = 2,
    SINGLESIGNON = 3
}</code>

Type safe enumeration mode

Type safe enumeration mode introduces a sealing class, and each enumeration member is expressed as a separate example:

This model has the following advantages:

<code class="language-csharp">public sealed class AuthenticationMethod
{
    private readonly string name;
    private readonly int value;

    public static readonly AuthenticationMethod FORMS = new AuthenticationMethod(1, "FORMS");
    public static readonly AuthenticationMethod WINDOWSAUTHENTICATION = new AuthenticationMethod(2, "WINDOWS");
    public static readonly AuthenticationMethod SINGLESIGNON = new AuthenticationMethod(3, "SSN");

    private AuthenticationMethod(int value, string name)
    {
        this.name = name;
        this.value = value;
    }

    public override string ToString()
    {
        return name;
    }
}</code>

Type safety:

    Class ensure that only effective values ​​are used.
  • Clear and concise: String indicates directly to each member. AuthenticationMethod
  • scalability:
  • can add added value without destroying the existing code.
  • Different type conversion
  • If needed, you can add an explicit type conversion to the
  • class, allow string to transform to enumeration (there are problems in this part of the code example, you need to correct it):

This allows easy conversion, for example:

The above is the detailed content of How Can I Get the String Representation of an Enum in C# More Elegantly?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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