DotNetRussell
DotNetRussell

Reputation: 9857

BitShift enum condition with int

This is mostly academic in nature. Just attempting to understand why this doesnt work and how to do it properly.

I store in my database a 0 1 or 2 where each represent a different status flag. (this cant be changed its in production)

In my code I have an enum

public enum Status{
    Active = 0,
    Voided = 1<<0,
    Refunded = 1<<1
}

What I want to do is turn the database value into my enum with as little code as possible.

I am sure I could do some crazy walk through like this

If(dbValue == 0)
   return Status.Active;
else if(dbValue == 1)
   return Stats.Voided;

... and so on

But I was curious if there was a simpler way.

Basically how do I quickly convert between an Int32 and a bit shifted enum with as little code as possible.

I tried doing this

   return dbVal | Status.Active;
   return 1 << Convert.Int32(dbValue);

and a couple other variations but nothign seems to work/

Upvotes: 1

Views: 221

Answers (1)

Timothy Shields
Timothy Shields

Reputation: 79441

For the enum you show, the following will work:

int dbValue = ...;
var status = (Status)dbValue;

If the database value can only take one of three values - 0 (Active), 1 (Voided), 2 (Refunded) - then it would probably be clearer to make your enum the following equivalent.

public enum Status
{
    Active = 0,
    Voided = 1,
    Refunded = 2
}

The bit shifts you use suggest a bit field, but that's not what you actually are dealing with. It wouldn't make sense to have Status.Voided | Status.Refunded;.

Upvotes: 4

Related Questions