8

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)

1

2 Answers 2

12

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();
Sign up to request clarification or add additional context in comments.

2 Comments

I am passing (int)enumId It can be 0 or 1. How can I map in this way
@Kgn-web check my edited answer, you need to cast int to enum
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();

}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.