Coder Perfect

Name of an enum string derived from a value

Problem

This is an example of an enum construct:

public enum EnumDisplayStatus
{
    None    = 1,
    Visible = 2,
    Hidden  = 3,
    MarkedForDeletion = 4
}

The enumerations in my database are referred by value. My question is how to convert the enum’s numeric representation to a string name.

Given 2 as an example, the outcome should be Visible.

Asked by jdee

Solution #1

With a simple cast, you may return the int to an enumeration member and then call ToString():

int value = GetValueFromDb();
var enumDisplayStatus = (EnumDisplayStatus)value;
string stringValue = enumDisplayStatus.ToString();

Answered by Kent Boogaart

Solution #2

You may get the string “Visible” without getting an EnumDisplayStatus object by doing the following:

int dbValue = GetDBValue();
string stringValue = Enum.GetName(typeof(EnumDisplayStatus), dbValue);

Answered by algreat

Solution #3

Try this:

string m = Enum.GetName(typeof(MyEnumClass), value);

Answered by Mandoleen

Solution #4

Use this:

string bob = nameof(EnumDisplayStatus.Visible);

Answered by James Cooke

Solution #5

The quickest and most compile-time method is to use the nameof expression.

Returns the enum’s literal type casing, or a class, struct, or any other type of variable in other situations (arg, param, local, etc).

public enum MyEnum {
    CSV,
    Excel
}


string enumAsString = nameof(MyEnum.CSV)
// enumAsString = "CSV"

Note:

Answered by Reap

Post is based on https://stackoverflow.com/questions/309333/enum-string-name-from-value