tags:

views:

95

answers:

2

Hi, 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 ?

A: 

As the FlagsAttribue is intended to mark your enumaration as a bit field, using negative number won't make much sense. Look at the binary representation (for int16):

 1 -> 0000000000000001b
 2 -> 0000000000000010b
 4 -> 0000000000000100b

-1 -> 1111111111111111b
-2 -> 1111111111111110b
-4 -> 1111111111111100b

As you can see, the negative enum values will behave as a bitwise combination of positive values. Taking an int32 as enums base you only have 32 distinct values available. So there is a maximum of 64 values using long(int64) as a base for your enumeration.

If you exceed this number, maybe another data structure would fit better, for exmple a List of enum values.

Frank Bollack
A: 

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.

Jason Williams