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)
CA1069: Enums should not have duplicate values.
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.
The GetValues method returns an array that contains a value for each member of the enumType enumeration.
Enumerations in Python are implemented by using the module named “enum“. Enumerations are created using classes. Enums have names and values associated with them.
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();
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With