Wednesday, July 20, 2011

Importance of Enumerations

Enumerations are simple value types that allow developers to choose from a list of constants.

Behind the scenes, an enumeration is just an ordinary integral number where every value has

a special meaning as a constant. However, because you refer to enumeration values using their

names, you don’t need to worry about forgetting a hard-coded number, or using an invalid


To define an enumeration, you use the block structure shown here:

public enum FavoriteColors







This example creates an enumeration named FavoriteColors with three possible values:

Red, Blue, and Yellow.

Once you’ve defined an enumeration, you can assign and manipulate enumeration values

like any other variable. When you assign a value to an enumeration, you use one of the predefined

named constants. Here’s how it works:

// You create an enumeration like an ordinary variable.

FavoriteColors buttonColor;

// You assign and inspect enumerations using a property-like syntax.

buttonColor = FavoriteColors.Red;

In some cases, you need to combine more than one value from an enumeration at once.

To allow this, you need to decorate your enumeration with the Flags attribute, as shown here:


public enum AccessRights


Read = 0x01,

Write = 0x02,

Shared = 0x04,


This allows code like this, which combines values using a bitwise or operator:

AccessRights rights = AccessRights.Read | AccessRights.Write | AccessRights.Shared;
You can test to see if a single value is present using bitwise arithmetic with the & operator

to filter out what you’re interested in:

if ((rights & AccessRights.Write) == AccessRights.Write)


// Write is one of the values.


Enumerations are particularly important in user-interface programming, which often has

specific constants and other information you need to use but shouldn’t hard-code. For example,

when you set the color, alignment, or border style of a button, you use a value from the appropriate



No comments :

Post a Comment