flag operator questions

C

Craig Buchanan

I am using flag as the identifier for various security settings. For
instance:

Public Enum SecurityEnum
Read=0
Write=1
Delete=2
...
End Enum

I have a few questions:
1). If I want to group a number of these rights into a role, should I
determine the xor result of all the rights that i need? or always xor the
rights?
2). What type of database field should i use for storage? Byte? What
size field?
3). Is there an easy way to determine the value of all bits being turned
on?
4). Does it matter if i define the values in the enum using 1,2,4 or
&h1,&h2,&h4?
5). What is the right 'numbering' for each successive bit? Powers of 2,
correct? In hex, would that be &h0,&h1,&h2,&h4,&h8,&h16...?
6). Can someone suggest a primer on using flags?

Thanks in advance,

Craig Buchanan
 
J

Jay B. Harlow [MVP - Outlook]

Craig,
1). If I want to group a number of these rights into a role, should I
determine the xor result of all the rights that i need? or always xor the
rights?
Huh? Do you mean "add" the rights together, you would use OR, you would use
Xor to toggle a right.

Dim rights As Security = Security.Read Or Security.Write

rights = rights Xor Security.Delete ' add Delete

rights = rights Xor Security.Delete ' remove Delete
2). What type of database field should i use for storage? Byte? What
size field?
I would use a Integer, unless I gave the enum a smaller type. Remember you
can define the Enum to the size you want using As Byte, Short, Integer, or
Long on the definition.

Public Enum Security As Byte
3). Is there an easy way to determine the value of all bits being turned
on?
I normally use the And operator

Dim mask As Security = Security.Read Or Security.Write
If (rights And mask) = mask Then
4). Does it matter if i define the values in the enum using 1,2,4 or
&h1,&h2,&h4?
Only when you get to 10 ;-) In VB.NET 2003 I sometimes use the Left Shift
operator

Public Enum Security None = 0
Read= 1 << 0
Write= 1 << 1
Delete= 1 << 2
Browse = 1 << 3
Update = 1 << 4
...
End Enum
5). What is the right 'numbering' for each successive bit? Powers of 2,
correct? In hex, would that be &h0,&h1,&h2,&h4,&h8,&h16...?
Powers of 2 starting with 1 as you cannot test the value 0 as being set, I
normally reserve it for "None".
6). Can someone suggest a primer on using flags?
Don't know of any specific primers per se, however the following links may
be useful:

http://msdn.microsoft.com/library/d...html/cpconEnumerationTypeNamingGuidelines.asp

Hope this helps
Jay
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top