Associating Enums with Strings in C#

Associating enums with strings in C#

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);

How to define an enum with string value?

You can't - enum values have to be integral values. You can either use attributes to associate a string value with each enum value, or in this case if every separator is a single character you could just use the char value:

enum Separator
{
Comma = ',',
Tab = '\t',
Space = ' '
}

(EDIT: Just to clarify, you can't make char the underlying type of the enum, but you can use char constants to assign the integral value corresponding to each enum value. The underlying type of the above enum is int.)

Then an extension method if you need one:

public string ToSeparatorString(this Separator separator)
{
// TODO: validation
return ((char) separator).ToString();
}

Can enums contain strings?

As others have said, no you cannot.

You can do static classes like so:

internal static class Breakout {
public static readonly string page="String1";
public static readonly string column="String2";
public static readonly string pagenames="String3";
public static readonly string row="String4";

// Or you could initialize in static constructor
static Breakout() {
//row = string.Format("String{0}", 4);
}
}

Or

internal static class Breakout {
public const string page="String1";
public const string column="String2";
public const string pagenames="String3";
public const string row="String4";
}

Using readonly, you can actually assign the value in a static constructor. When using const, it must be a fixed string.

Or assign a DescriptionAttribute to enum values, like here.

String representation of an Enum

Try type-safe-enum pattern.

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;
}

}

Update
Explicit (or implicit) type conversion can be done by

  • adding static field with mapping

    private static readonly Dictionary<string, AuthenticationMethod> instance = new Dictionary<string,AuthenticationMethod>();
    • n.b. In order that the initialisation of the the "enum member" fields doesn't throw a NullReferenceException when calling the instance constructor, be sure to put the Dictionary field before the "enum member" fields in your class. This is because static field initialisers are called in declaration order, and before the static constructor, creating the weird and necessary but confusing situation that the instance constructor can be called before all static fields have been initialised, and before the static constructor is called.
  • filling this mapping in instance constructor

    instance[name] = this;
  • and adding user-defined type conversion operator

    public static explicit operator AuthenticationMethod(string str)
    {
    AuthenticationMethod result;
    if (instance.TryGetValue(str, out result))
    return result;
    else
    throw new InvalidCastException();
    }

Enum of strings in C#

The way to approach problems like this is for the class in question to have a private constructor, and to have public static field/properties that are initialized with values of that instance. This is a way of having a fixed finite number of immutable instances of that type, while still allowing methods to accept parameters of that type.

The following code is valid C# 6.0.

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

public string Value { get; private set; }

public static Command SET_STB_MEDIA_CTRL { get; } = new Command("SET STB MEDIA CTRL ");
public static Command ECHO { get; } = new Command("ECHO");
public static Command SET_CHANNEL { get; } = new Command("SET CHANNEL ");
public static Command GET_VOLUMN { get; } = new Command("GET VOLUMN");
public static Command GET_MAX_VOLUMN { get; } = new Command("GET MAX VOLUMN ");
public static Command SET_STB_MEDIA_LIST { get; } = new Command("SET STB MEDIA LIST ");
}

enum set to string and get sting value when need

Unfortunately that's not possible. Enums can only have a basic underlying type (int, uint, short, etc.). If you want to associate the enum values with additional data, apply attributes to the values (such as the DescriptionAttribute).

public static class EnumExtensions
{
public static TAttribute GetAttribute<TAttribute>(this Enum value)
where TAttribute : Attribute
{
var type = value.GetType();
var name = Enum.GetName(type, value);
return type.GetField(name)
.GetCustomAttributes(false)
.OfType<TAttribute>()
.SingleOrDefault();
}

public static String GetDescription(this Enum value)
{
var description = GetAttribute<DescriptionAttribute>(value);
return description != null ? description.Description : null;
}
}

enum MyEnum
{
[Description("abc")] Name1,
[Description("xyz")] Name2,
}

var value = MyEnum.Name1;
if (value.GetDescription() == "abc")
{
// do stuff...
}

How to set string in Enum C#?

Do this:

private IddFilterCompareToCurrent myEnum = 
(IddFilterCompareToCurrent )Enum.Parse(typeof(IddFilterCompareToCurrent[1]),domainUpDown1.SelectedItem.ToString());

[Enum.parse] returns an Object, so you need to cast it.



Related Topics



Leave a reply



Submit