Utilising Enumeration (Enum) Types in Your Code

Utilising Enumeration (Enum) Types in Your Code

Enumeration (Enum) Types

Enum types are a special value type that contains a group of constants, by default these constants take on the integer type. To define an enumeration, the keyword ‘enum’ should be used followed by an identifier.


                    enum Severity
{
	Low,
	Medium,
	High
}

                

Enumeration types are useful when trying to represent a choice or combination of choices.

Each underlying member in the enum has an associated value of type int, by default these members are assigned 0, 1, 2 … (n -1) where n is the total number of enum members.

Enum days of the week example

If you wish to change these default values you may explicitly define values for each enum member. For example

enum Severity
{
	Low=1,
	Medium=10,
	High=100
}

Enumeration Conversion

It is possible to explicitly convert an enum member to a variable that is the same (or compatible) with the member type – normally int. If you have not assigned a value to the enum member, the cast will result in the default value that has been taken on following the pattern of increments of 1.

It is also possible to cast one enum type to another but just as before, this must be an explicit cast.

Bit Flags and Enumeration Types

Earlier it was mentioned that you might want to use an enumeration type to represent a combination of choices. If this is the case, you should consider defining the members as a bit-field, this will prevent ambiguities. Consecutive members should be in powers of two.

The bitwise logical operators, |(OR) and & (AND) can then be used to combine and distinguish choices. We can add an indication that we intend to use an enumeration type as a collection of bit fields with the ‘Flags’ attribute. When the Flags attribute is used, the convention is that the name of the enum is a plural


                    using System;

[Flags]
public enum Severities
{
	Low= 0b_0000_0000,
	LowMedium = 0b_0000_0001,
	Medium= 0b_0000_0010,
	MediumHigh = 0b_0000_0100,
	High= 0b_0000_1000
}

public class Program
{
	public static void Main()
	{
		Severities openSeverities = Severities.Low | Severities.Medium | Severities.High;
		Console.WriteLine(openSeverities);

		Severities priorities = Severities.High | Severities.MediumHigh;

		Severities toDo = openSeverities & priorities;
		Console.WriteLine(toDo);
	}
}
                

Other operators will work with the enumerator type, these include:

= == !=
< > <=
>= +
^ & |
~ += -=
++ sizeOf

For more information on these operations please visit the Microsoft documentation:

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/expressions#enumeration-logical-operators