For most of us, enumerations provide a means of selecting one of many options. What some of us don't know is that they also provide a means for us to specify more than one option at a time in one variable or argument. I came to this realization when I happened to visit a couple of students who were working on a college project in Visual Basic 6 recently. A part of their application allowed a user to select one or more of a set of eight options. To do this, they had 8 Boolean variables to determine which options were selected and I had to come in and point out to them that using an enumeration was the way to go.
First up, the Basics - Boolean algebra
To start with, I will mention that this article presents Visual Basic .NET code, and not VB6 as the students had. I will take you on a quick recap of the basics of Boolean algebra. We will assume for the purposes of this article that True corresponds to 1 and False corresponds to 0, even though savvy VB programmers will argue that True equals -1.
• The AND operation is a multiplication operation
• The OR operation performs an addition
• 0 AND 0 = 0
• 1 AND 0 = 0
• 1 AND 1 = 1
• 0 OR 0 = 0
• 1 OR 0 = 1
• 1 OR 1 = 1
That's as deep as I will go. We will accept these to be facts and debate them if we have to in another topic. These are the very basic rules for us to understand how to specify many options in one variable.
Setting many options in one variable of an enumeration type is known as setting Flags. .NET provides us with the 'Flags' attribute for our enumerations. Applying the Flags attribute is as simple as placing <FLAGS()>in Visual Basic .NET and [Flags()] in C# before the enumerations declaration. For any of this to make sense, we will need a complete but simple example.
Our test application will have one enumeration called Stuff that will be used to determine which of 4 items a user has selected. The four items are Item1 through to Item4.
The enumeration is defined thus:
<FLAGS()>Public Enum Stuff
Item1 = 1
Item2 = 2
Item3 = 4
Item4 = 8
Now, some of you may be wondering why I am counting in this odd way. Another small set of you will notice that I am counting in powers of 2. Going back to the old saying I heard before I knew what a computer was, "A computer only understands 1 and 0". This was someone's way of saying that a computer is a digital device, and works on binary data. The logic behind numbering the values this way will become apparent towards the end of the article.