7

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)

Kgn-web
  • 7,047
  • 24
  • 95
  • 161

2 Answers2

11

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();
Kamil Budziewski
  • 22,699
  • 14
  • 85
  • 105
2

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();

}
Masoud Andalibi
  • 3,168
  • 5
  • 18
  • 44