574

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.

AustinWBryan
  • 3,249
  • 3
  • 24
  • 42
jdee
  • 11,612
  • 10
  • 38
  • 36

15 Answers15

722

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

int value = GetValueFromDb();
var enumDisplayStatus = (EnumDisplayStatus)value;
string stringValue = enumDisplayStatus.ToString();
AustinWBryan
  • 3,249
  • 3
  • 24
  • 42
Kent Boogaart
  • 175,602
  • 35
  • 392
  • 393
  • 14
    Update: only certain overloads using IFormatProvider are deprecated. ToString() is fine. See http://groups.google.com/group/DotNetDevelopment/browse_thread/thread/dcdbeae086360208 – AndyM Apr 15 '09 at 09:37
  • What is the behavior in case of `enum Foo { A = 1, B= 1 }`? – dbkk Jul 05 '11 at 06:26
  • 5
    @dbkk the documentation states that with regards to enums "your code should not make any assumptions about which string will be returned." because of the precise situation you quote. see http://msdn.microsoft.com/en-us/library/16c1xs4z.aspx – Paul D'Ambra Jul 25 '11 at 12:41
  • 11
    An uptodated solution: http://msdn.microsoft.com/en-us/library/system.enum.getname%28v=vs.110%29.aspx – Jack Jul 18 '14 at 01:13
  • 7
    shorter: var stringValue = ((EnumDisplayStatus)value).ToString() – redwards510 Jan 12 '17 at 18:17
255

If you need to get a string "Visible" without getting EnumDisplayStatus instance you can do this:

int dbValue = GetDBValue();
string stringValue = Enum.GetName(typeof(EnumDisplayStatus), dbValue);
algreat
  • 8,592
  • 5
  • 41
  • 54
204

Try this:

string m = Enum.GetName(typeof(MyEnumClass), value);
nawfal
  • 70,104
  • 56
  • 326
  • 368
Mandoleen
  • 2,591
  • 2
  • 20
  • 17
94

Use this:

string bob = nameof(EnumDisplayStatus.Visible);
Sach
  • 10,091
  • 8
  • 47
  • 84
James Cooke
  • 1,086
  • 8
  • 7
48

The fastest, compile time solution using nameof expression.

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

public enum MyEnum {
    CSV,
    Excel
}


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

Note:

  • You wouldn't want to name an enum in full uppercase, but used to demonstrate the case-sensitivity of nameof.
Reap
  • 1,047
  • 13
  • 16
30

you can just cast it

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

ah.. kent beat me to it :)

Hath
  • 12,606
  • 7
  • 36
  • 38
20

SOLUTION:

int enumValue = 2; // The value for which you want to get string 
string enumName = Enum.GetName(typeof(EnumDisplayStatus), enumValue);

Also, using GetName is better than Explicit casting of Enum.

[Code for Performance Benchmark]

Stopwatch sw = new Stopwatch (); sw.Start (); sw.Stop (); sw.Reset ();
double sum = 0;
int n = 1000;
Console.WriteLine ("\nGetName method way:");
for (int i = 0; i < n; i++) {
   sw.Start ();
   string t = Enum.GetName (typeof (Roles), roleValue);
   sw.Stop ();
   sum += sw.Elapsed.TotalMilliseconds;
   sw.Reset ();
}
Console.WriteLine ($"Average of {n} runs using Getname method casting way: {sum / n}");
Console.WriteLine ("\nExplicit casting way:");
for (int i = 0; i < n; i++) {
   sw.Start ();
   string t = ((Roles)roleValue).ToString ();
   sw.Stop ();
   sum += sw.Elapsed.TotalMilliseconds;
   sw.Reset ();
}
Console.WriteLine ($"Average of {n} runs using Explicit casting way: {sum / n}");

[Sample result]

GetName method way:
Average of 1000 runs using Getname method casting way: 0.000186899999999998
Explicit casting way:
Average of 1000 runs using Explicit casting way: 0.000627900000000002
Naveen Kumar V
  • 2,559
  • 2
  • 29
  • 43
  • 2
    This is a copy of a 7 year old answer. Can you explain why your's is better than the original? – nvoigt Feb 22 '19 at 09:20
  • @nvoigt Because, if I am correct, the ToString() API on Enum is now obsolete. [https://learn.microsoft.com/en-us/dotnet/api/system.enum.tostring?view=netframework-4.8] – Naveen Kumar V Feb 22 '19 at 10:02
  • So... at least two other answers already provide the code you posted. What does your's provide over the one from Mandoleen or algreat? – nvoigt Feb 22 '19 at 10:44
  • @nvoigt They did not mention about its performance compared to Explicit casting. Is this sufficient for you to like my answer? :p Thanks anyway, I hope it will help someone. :) – Naveen Kumar V Feb 22 '19 at 11:00
  • 1
    We seem to have a communication problem. Are you on a mobile device or maybe did you not scroll down far enough? There are two exact copies of your answer from 7 years back. I named the answerers, so they should be easy to find. What does your answer provide that has not been here for at least 7 years already? – nvoigt Feb 22 '19 at 13:35
15

DB to C#

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

C# to DB

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

Just need:

string stringName = EnumDisplayStatus.Visible.ToString("f");
// stringName == "Visible"
Al3x_M
  • 214
  • 3
  • 3
  • 2
    in most cases, this is pretty much identical to the top answer from 10 years ago; the addition of the `"f"` specifier is nuanced, and may or may not be what the caller wants (it depends on: what they want): https://learn.microsoft.com/en-us/dotnet/standard/base-types/enumeration-format-strings – Marc Gravell Nov 29 '18 at 12:50
  • 1
    I didn't pay attention to the date ahah. I think it is good to update a bit the old solution like this one. I won't be the last one to open this page. And thanks for your precision! :) – Al3x_M Nov 29 '18 at 16:39
8

Given:

enum Colors {
    Red = 1,
    Green = 2,
    Blue = 3
};

In .NET 4.7 the following

Console.WriteLine( Enum.GetName( typeof(Colors), Colors.Green ) );
Console.WriteLine( Enum.GetName( typeof(Colors), 3 ) );

will display

Green
Blue

In .NET 6 the above still works, but also:

Console.WriteLine( Enum.GetName( Colors.Green ) );
Console.WriteLine( Enum.GetName( (Colors)3 ) );

will display:

Green
Blue
StackOverflowUser
  • 945
  • 12
  • 10
6

i have used this code given below

 CustomerType = ((EnumCustomerType)(cus.CustomerType)).ToString()
Biddut
  • 418
  • 1
  • 6
  • 17
5

For getting the String value [Name]:

EnumDisplayStatus enumDisplayStatus = (EnumDisplayStatus)GetDBValue();
string stringValue = $"{enumDisplayStatus:G}"; 

And for getting the enum value:

string stringValue = $"{enumDisplayStatus:D}";
SetDBValue(Convert.ToInt32(stringValue ));
Muhammad Aqib
  • 709
  • 7
  • 14
4

Just cast the int to the enumeration type:

EnumDisplayStatus status = (EnumDisplayStatus) statusFromDatabase;
string statusString = status.ToString();
Vivek Jain
  • 3,811
  • 6
  • 30
  • 47
lacop
  • 2,024
  • 4
  • 22
  • 36
1

You can try this

string stringValue=( (MyEnum)(MyEnum.CSV)).ToString();
Biddut
  • 418
  • 1
  • 6
  • 17
0

Another option (inspired by PowerShell) is to use the Type.GetEnumName() method:

int enumValue = 2;
string enumName = typeof(EnumDisplayStatus).GetEnumName(enumValue);

Testing indicates it to be marginally faster than the Enum.GetName() method (about 4% over 1e8 iterations).

andronoid
  • 25
  • 6