How can I use the string value of a C# enum value in a case statement?

Viewed 77313

I have defined a C# enum as

public enum ORDER
{
    ...
    unknown,
    partial01,
    partial12,
    partial23,
}

and can use its value as a string as in:

            string ss = ORDER.partial01.ToString();

However when I try to use it in a case statement it fails to compile:

string value = ...
switch (value)
{
    case null:
        break;
    case "s":
        // OK
        break;
    case ORDER.partial01.ToString():
        // compiler throws "a constant value is expected"

        break;
  ...

I thought enums were constants. How do I get around this?

(I cannot parse the value into an enum as some of the values are outside the range)

12 Answers

Use Extension

      public static string ToGender(this Gender enumValue)
        {
            switch (enumValue)
            {
                case Gender.Female:
                    return "Female";
                case Gender.Male:
                    return "Male";
                default:
                    return null;
            }
        }

Example

Gender.Male.ToGender();
Related