How to get string value from Enum

I got confused with Enum. This is my listing

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 - unable to convert string to enum.Status

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

How to set objecj client status properties using enumeration state.?

(Not if - Else or the ladder of switching)

+4
source share
2 answers

You just need to call .ToString

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

ToString () on Enum from MSDN

If you passed an enumeration identifier, you can run:

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

It distinguishes an integer from an Enum value, and then calls ToString()

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

public void CreateStatus(Status status , string userName)

and name it:

CreateStatus(1,"whatever");

and drop to the line:

t.Status = status.ToString();
+2
source

ToString() .

enum Status
{
   Success = 1,
   Error = 0
}

string foo = Status.Success.ToString(); 

Update

, Enum , :

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

}
+1

Source: https://habr.com/ru/post/1669788/


All Articles