tags:

views:

2411

answers:

4

I have an enum construct like this:

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

In my database, the enumerations are referenced by value. My question is, how can i turn the number representation of the enum, back to the string name. for example, given '2' the result should be 'visible'.

+6  A: 

You can convert the int back to an enumeration member with a simple cast, and then call ToString():

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

HTH, Kent

Kent Boogaart
Enum.ToString() is now deprecated
AndyM
Update: only certain overloads using IFormatProvider are deprecated. ToString() is fine. See http://groups.google.com/group/DotNetDevelopment/browse_thread/thread/dcdbeae086360208
AndyM
+1  A: 

you can just cast it

int dbValue = 2;
EnumDisplayStatus enumValue = (EnumDisplayStatus)dbValue;
string stringName = enumValue.ToString(); //Visible

ah.. kent beat me to it :)

Hath
A: 

Just cast the int to the enumeration type:

        EnumDisplayStatus status = (EnumDisplayStatus) statusFromDatabase;
        string statusString = status.ToString ();
lacop
A: 

DB to C#

EnumDisplayStatus status = (EnumDisplayStatus)int.Parse(GetValueFromDb());

C# to DB

string dbStatus = ((int)status).ToString();
MisterTom