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)
Answer
You just need to call .ToString
t.Status = Status.Success.ToString();
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();
No comments:
Post a Comment