Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get string value from Enum [duplicate]

Tags:

c#

enums

asp.net

I am confused with Enum. This is my enum

enum Status
{
   Success = 1,
   Error = 0
}


public void CreateStatus(int enumId , string userName)
{
     Customer t = new Customer();
     t.Name = userName;
    // t.Status = (Status)status.ToString(); - throws build error
     t.Status = //here I am trying if I pass 1 Status ="Success", if I pass 0 Status = "Error"

}

Error - Cannot convert string to enum.Status

public class Customer
{
  public string Name { get; set;}
  public string Status {get; set;}
}

How do I set the Status properties of the customer objecj using the Enum Status.?

(No If-Else or switch ladder)

like image 612
Kgn-web Avatar asked Feb 15 '17 06:02

Kgn-web


People also ask

Can Enum have duplicate values?

CA1069: Enums should not have duplicate values.

How to Get values from Enum?

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.

What does Enum GetValues return?

The GetValues method returns an array that contains a value for each member of the enumType enumeration.

Does python have Enums?

Enumerations in Python are implemented by using the module named “enum“. Enumerations are created using classes. Enums have names and values associated with them.


2 Answers

You just need to call .ToString

 t.Status = Status.Success.ToString();

ToString() on Enum from MSDN

If you have enum Id passed, you can run:

t.Status = ((Status)enumId).ToString();

It casts integer to Enum value and then call ToString()

EDIT (better way): You can even change your method to:

public void CreateStatus(Status status , string userName)

and call it:

CreateStatus(1,"whatever");

and cast to string:

t.Status = status.ToString();
like image 83
Kamil Budziewski Avatar answered Oct 04 '22 03:10

Kamil Budziewski


Its easy you can use ToString() method to get the string value of an enum.

enum Status
{
   Success = 1,
   Error = 0
}

string foo = Status.Success.ToString(); 

Update

Its easier if you include the type of Enum within your method's inputs like below:

public void CreateStatus(Status enums, string userName)
{
     Customer t = new Customer();
     t.Name = userName;
     t.Status = enums.Success.ToString();

}
like image 41
Masoud Andalibi Avatar answered Oct 04 '22 01:10

Masoud Andalibi