Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum String Name from Value

Tags:

c#

enums

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.

like image 477
jdee Avatar asked Nov 21 '08 16:11

jdee


People also ask

How do you find the enum value of a string?

Get the value of an Enum To get the value of enum we can simply typecast it to its type. In the first example, the default type is int so we have to typecast it to int. Also, we can get the string value of that enum by using the ToString() method as below.

Can we convert enum to string?

We can convert an enum to string by calling the ToString() method of an Enum.

Can we assign string value to enum in C#?

Since C# doesn't support enum with string value, in this blog post, we'll look at alternatives and examples that you can use in code to make your life easier. The most popular string enum alternatives are: Use a public static readonly string. Custom Enumeration Class.

What is Enumtype?

An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it.


1 Answers

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(); 
like image 100
Kent Boogaart Avatar answered Oct 04 '22 09:10

Kent Boogaart