Final Words on Enums
to the ToString method as shown in the forthcoming code:
Dim MsgState As MessageFlagEnum.IsAccessed | MessageFlagEnum.IsArchived
Debug.WriteLine(MsgState.ToString("F"))
This is a little cumbersome; however, Microsoft has developed a cleaner approach to making the enumeration
think it's a collection of bit flags. We can use the Flags attribute to denote bit−field or bit−flag semantics.
While the runtime itself does not distinguish between traditional enumerations and bit fields, you can make
this distinction in your code via the Flags attribute, allowing you to use bitwise operators transparently on all
bit fields. At runtime, therefore, you get what you ask for. This amended Enum portrays the use of the flags
attribute seen here decorating MessageFlagEnum:
<Flags>
Public Enum MessageFlagEnum
MessageFlag = 0x0001
IsAccessed = 0x0002
IsArchived = 0x0004
IsDeleted = 0x0008
NewMessage = 0x0016
End Enum
Final Words on Enums
Here are some final considerations before you implement the Enum type in your applications:
• Enumerations can represent any of the ordinal built−in data types (except Char). Remember, the
"magic words" are "magic numbers," not "magic Booleans" or "magic characters."
• You can assign a value of the underlying type to an enumeration and vice versa (no cast is required by
the runtime).
• You can create an instance of an enumeration and call the methods of System.Enum, as well as any
methods defined on the enumeration's underlying type. However, some languages might not allow
you to pass an enumeration as a parameter when an instance of the underlying type is required (or
vice versa).
• Enums cannot define their own methods.
• Enums cannot implement interfaces.
• Enums cannot define properties and events.
• Reduce operations with Enums that create a lot of boxing/unboxing code as demonstrated earlier in
this chapter. Since some of the methods entail casting symbol values to objects, moving values to the
heap may detract from performance requirements. Try re−writing your code to use minimal boxing
overhead.
• Finally, if only one class or object is using the Enum, don't nest or encapsulate it in the class. It won't
be long before other classes in the application will need the Enum, and you'll be forced to define it at
the level of those classes as well. This may not seem problematic for a small Enum, but imagine the
difficulties if dozens of methods were depending on that Enum. Nesting also detracts from the
elegant Enum semantics you have at your disposal, because Friend classes still have to access the
encapsulating object's interface before they can reference the Enum. As you have seen, all Enums
defined for the framework are identified at the same level as all standard classes.
Other than noting the few items in the above list, the enumeration is an especially powerful and fun construct
to work with.
Note The code for the above enumerations is the Enumerations project in the Vb7cr solution.
255