6

I have an enum type defined like so:

public enum Status
{
    Active=1,
    InActive=0
}

in my method can I cast the parameter into the enum like this:

public string doSomething(string param1, int status)
{
//will this work?      
Account.Status = (Status) status;
//or do i need to test one by one like this
if(status == 0)
{
 Account.Status = Status.Inactive;
 //and so on...
} // end if
}  // end doSomething
pb2q
  • 58,613
  • 19
  • 146
  • 147
sirbombay
  • 409
  • 2
  • 6
  • 17

3 Answers3

2

Yes, you can do a straight cast from int to enum (given that an enum representation of that integer exists).

If you need to check whether the enum exists before parsing use Enum.IsDefined i.e.

if (Enum.IsDefined(typeof(Status), status))
{
    Account.Status = (Status)status;
}
James
  • 80,725
  • 18
  • 167
  • 237
1

well of course you can do that. just try and see.

you can also cast the other way

(int)Account.Status

it's possible to cast Enum to int and vice versa, because every Enum is actually represented by an int per default. You should manually specify member values. By default it starts from 0 to N.

if you try to convert an enum value that does not exist it'll work, but wont give you an enum value if you try to compare it the any value you have in the enum

No Idea For Name
  • 11,411
  • 10
  • 42
  • 70
1

Just check if the int is a valid value for Status and then do a conversion.

public string doSomething(string param1, int status)
{
    if (IsValidEnum<Status>(status))
    {
        Account.Status = (Status)status;
    }
    ...
}

private bool IsValidEnum<T>(int value)
{
    var validValues = Enum.GetValues(typeof(T));
    var validIntValues = validValues.Cast<int>();
    return validIntValues.Any(v => v == value);
}

In de else of the if you can throw an exception if you wish.

Alex Siepman
  • 2,499
  • 23
  • 31