Associating enums with strings in C#

Boris Callens picture Boris Callens · Mar 10, 2009 · Viewed 398.8k times · Source

I know the following is not possible because the Enumeration's type has to be an int

enum GroupTypes
{
    TheGroup = "OEM",
    TheOtherGroup = "CMB"
}

From my database I get a field with incomprehensive codes (the OEM and CMBs). I would want to make this field into an enum or something else understandable. Because if the target is readability, the solution should be terse.

What other options do I have?

Answer

Even Mien picture Even Mien · Aug 27, 2009

I like to use properties in a class instead of methods, since they look more enum-like.

Here's a example for a Logger:

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

    public string Value { get; set; }

    public static LogCategory Trace   { get { return new LogCategory("Trace"); } }
    public static LogCategory Debug   { get { return new LogCategory("Debug"); } }
    public static LogCategory Info    { get { return new LogCategory("Info"); } }
    public static LogCategory Warning { get { return new LogCategory("Warning"); } }
    public static LogCategory Error   { get { return new LogCategory("Error"); } }
}

Pass in type-safe string values as a parameter:

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

Usage:

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