Enums

The enumeration type, also known as enum, delivers an efficient means of defining a named integral constant set, which can be assigned to a variable.

The significance of its use is defining a set like the days of the week in which there will only ever be 7 values. Review enum use in defining those values below:

enum WorkDays { Mon, Tues, Wed, Thurs, Fri };
enum WorkMonths : byte { February, March, April, May, September,
October, November, December };

The default data type of each element is int, but types can be specified as seen in the previous code example.

Enum offers two important advantages: the valid values for the variable are specified for client code, and IntelliSense (in Visual Studio) lists defined values.

When values for elements are not specified in the enumerator list, values are automatically incremented 1 unit. Always create a logical default value, and set it to zero. This results in all enums having the value when not explicitly assigned (on creation).

Enum elements of the enumerator list take any values, and accept computed values. Review an example below:

enum DeviceState
{
	PWROff = 0,
	PWROn = 50,
	Sleep = 25,
	Hibernation = Sleep - 12
}

BIT FLAGS

Enumeration types can define bit flags. This allows an enum instance to hold any combination of values defined in the list. If statements and other control statements then test for these values. Apply the System.FlagsAttribute, and define values appropriate for bitwise operations to create bit flag enums. Also, include a named constant with a zero value indicating no flags are set. Never assign the value of zero unless it means “no flags set.”

Review the following bit flag enum example:

[Flags]
enum DayzTwo
{
	Zero = 0x0,
	Sun = 0x1,
	Mon = 0x2,
	Tues = 0x4,
	Wed = 0x8,
	Thurs = 0x10,
	Fri = 0x20,
	Sat = 0x40
}
class AClass
{
	DayzTwo meetingDayzTwo = Days2.Wed| Days2.Fri;
}

Review an example of using the bitwise OR operator to set a flag below:

// Initialize with 2 flags, use bitwise OR.
meetDayz = DayzTwo.Tues | DayzTwo.Thurs;

// Set an extra flag, use bitwise OR.
meetDayz = meetDayz | DayzTwo.Fri;
Console.WriteLine("The days of meetings follow: {0}", meetDayz);

// Delete a flag, use bitwise XOR.
meetDayz = meetDayz ^ DayzTwo.Tues;
Console.WriteLine("The days of meetings follow {0}", meetDayz);

VALUE ACCESS

Enums are actually all instances of the System.Enum type. Though classes cannot derive from System.Enum, its methods can gather information and modify values. Review an example below:

string st = Enum.GetName(typeof(Dayz), 6);
Console.WriteLine(st);
Console.WriteLine("Dayz Enum values follow:");
foreach (int x in Enum.GetValues(typeof(Dayz)))
	Console.WriteLine(x);
Console.WriteLine("Dayz Enum names follow:");
foreach (string st2 in Enum.GetNames(typeof(Dayz)))
	Console.WriteLine(st2);