Home >Backend Development >C++ >How Can I Associate Strings with Enums in C#?

How Can I Associate Strings with Enums in C#?

Linda Hamilton
Linda HamiltonOriginal
2025-01-13 18:17:43611browse

How Can I Associate Strings with Enums in C#?

Associating Strings with Enums in C#

Creating enums with string values is not directly supported in C# due to the intrinsic integer nature of enums. However, there are several alternative options to achieve similar functionality.

Properties in a Class:

One approach is to utilize properties within a class. Properties resemble enums while providing the flexibility of using string values. For instance, consider the following class:

public class LogCategory
{
    private LogCategory(string value) { Value = value; }

    public string Value { get; private set; }

    public static LogCategory Trace { get { return new LogCategory("Trace"); } }
    public static LogCategory Debug { get { return new LogCategory("Debug"); } }
    ...
}

Type-Safe String Parameters:

Another option is to pass type-safe string values as parameters to methods. This ensures code readability and safety. For example:

public static void Write(string message, LogCategory logCategory)
{
    var log = new LogEntry { Message = message };
    Logger.Write(log, logCategory.Value);
}

Usage:

Both approaches allow for intuitive and readable usage:

Logger.Write("This is almost like an enum.", LogCategory.Info);

The above is the detailed content of How Can I Associate Strings with Enums in C#?. 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