Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

flagsattribute - negative values?

Tags:

.net

flags

I have a enum with a flagsattribute, which i use to represent permissions. I use it to compare if (CurrentPermissions & Permission1 == Permission1) etc...

[FlagsAttribute]
enum MyPermission
{
  None = 0,
  Permission1 = 1,
  Permission2 = 2,
  Permission3 = 4,
  Permission4 = 8,...
  ..................
  and so on

}

However, we reach a max limit. Can i use negative values like -1, -2, -4 etc. once i run out of enum values ?

like image 964
user157476 Avatar asked Feb 21 '26 08:02

user157476


1 Answers

You can define entries with any values you like within a Flags enum. Two common ones would be zero and 0xffffffff (-1) because these can be useful values to represent "all options disabled" and "all options enabled" values, e.g

enum DrawingOptions
{
   None         = 0,

   DrawLines    = 1 << 0,
   FillShapes   = 1 << 1,
   Antialias    = 1 << 2,

   BestQuality  = 0xffffffff
}

(If you add a new option, any code that enabled "BestQuality" will automatically have that option enabled, so you won't have to search through your code to update everything)

However, negative numbers other than -1 aren't likely to be very useful, as Frank Bollack has already answered.

You may also have to be rather careful with negative numbers when the size of your enum (byte, int32, int64) changes.

like image 131
Jason Williams Avatar answered Feb 23 '26 23:02

Jason Williams



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!