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

How Can I Associate Strings with Enums in C#?

Linda Hamilton
Release: 2025-01-13 18:17:43
Original
548 people have browsed it

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"); } }
    ...
}
Copy after login

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);
}
Copy after login

Usage:

Both approaches allow for intuitive and readable usage:

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

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!

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