Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can enums contain strings? [duplicate]

Tags:

string

c#

enums

How can I declare an enum that has strings for values?

private enum breakout {            
    page = "String1",
    column = "String2",
    pagenames = "String3",
    row = "String4"
}
like image 781
Geek Avatar asked Jun 09 '11 19:06

Geek


2 Answers

No they cannot. They are limited to numeric values of the underlying enum type.

You can however get similar behavior via a helper method

public static string GetStringVersion(breakout value) {
  switch (value) {
    case breakout.page: return "String1";
    case breakout.column: return "String2";
    case breakout.pagenames: return "String3";
    case breakout.row: return "String4";
    default: return "Bad enum value";
  }
}
like image 92
JaredPar Avatar answered Oct 04 '22 17:10

JaredPar


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.

like image 33
CodeNaked Avatar answered Oct 04 '22 19:10

CodeNaked