Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the bitmask value back out of an enum with the flag attribute in C#?

In our database we have a bitmask that represents what types of actions a user can make.

In our C# client when we retrieve this integer value from the database we construct an enum/flag. It looks somewhat like the following:

[Flags]
public enum SellPermissions
{
    Undefined = 0,
    Buy = 1,
    Sell = 2,
    SellOpen = 4,
    SellClose = 8
    // ...
}

In our application I have an edit permissions page which I then use to modify the value of this enum using the bitwise OR on different enum values.

permissions = SellPermisions.Buy | SellPermissions.Sell;

Now, after these changes are made, in my database call I need to call an update/insert sproc which is expecting an integer value.

How do I get the integer bitwise value back out of my enum/flag so I can set the modified permissions in the database?

like image 922
Yohan Avatar asked Jan 29 '26 08:01

Yohan


2 Answers

I was able to do it by casting the variable to an int.

int newPermissions = (int)permissions.
like image 88
Eric Olsson Avatar answered Jan 30 '26 20:01

Eric Olsson


int permissionsValue = (int) permissions;
like image 21
Manish Basantani Avatar answered Jan 30 '26 20:01

Manish Basantani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!