Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Associating enums with strings in C#

Tags:

c#

.net

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?

like image 801
Boris Callens Avatar asked Mar 10 '09 15:03

Boris Callens


People also ask

How do I assign an enum to a string?

There are two ways to convert an Enum to String in Java, first by using the name() method of Enum which is an implicit method and available to all Enum, and second by using toString() method.

Can string be used with enum?

As far as I know, you will not be allowed to assign string values to enum. What you can do is create a class with string constants in it.

Can we have string enum C#?

Since C# doesn't support enum with string value, in this blog post, we'll look at alternatives and examples that you can use in code to make your life easier. The most popular string enum alternatives are: Use a public static readonly string. Custom Enumeration Class.


1 Answers

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

Here's an example for a Logger:

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"); } }     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); 
like image 113
Even Mien Avatar answered Sep 18 '22 11:09

Even Mien