Concept of Enumerations
In the last chapter, we learned about the struct, which is a C# type and is similar to a class, encapsulating data and functionality, that is, variables and methods. We saw that a struct can have a custom constructor, but will always have a default parameterless constructor , and the struct can contain properties for accessing the private members. In terms of accessibility, we saw that the struct could be made readonly, which means all fields automatically become set as readonly. However, we learned that from C# 8 individual fields could be set to have the readonly access, thereby leaving other fields to remain readable and writeable. Finally, we learned that structs are value types, whereas a class is a reference type.
We will now look at another structure called the enumeration, or enum as it is also called. Enumerations are essentially a group of integer values , which have been assigned names with the aim of making the code more readable. In Chapter 10 on iteration, we talked about magic numbers and how they are not acceptable when we wish to have clean code. Well, the enumeration helps us avoid the use of “magic numbers” by assigning names to them.
We use the keyword enum to identify the enumeration, which is used to hold a set of named integer constants . In C# an enumeration is a value data type, which means it will not inherit and has its own values. As we know from constants, the values do not change, so when we declare the constants in an enumeration, they cannot be changed in the code. As we said earlier, the “nice thing” about using an enumeration to declare constants is that we use descriptive names for the constants, thereby making them more user-friendly and helping the code to be more readable. We could say that they fit in well with the concept of clean code.
Defining an Enumeration
In its basic form, the simplest way to declare an enumeration is to give the enumeration a name and then list all the possible names in a set of braces after the enumeration's name. We use the enum keyword as a prefix to the enumeration name, so that the compiler understands that the definition is an enumeration. By default, an enumeration list makes the first item in the curly braces have a value of 0 with each remaining value being incremented by 1.
Enumeration Examples
Example 1
We will use this example in our code later, but what we might be surprised to hear is that the DayOfWeek enumeration is part of .NET. So enumerations exist in the real world.
Example 2
Example 3
Example 4
Example 5
Enumerated Values: Use and Scope
In C# we declare an enumeration anywhere and, like other items declared within a class , the methods of the class are able to use the values of the enumeration list. Our application code simply needs to use the name of the enumeration and the value of the item within the list.
Let's code some C# and build our programming muscle .
- 1.
Right-click the solution CoreCSharp.
- 2.
Choose Add.
- 3.
Choose New Project.
- 4.
Choose Console App from the listed templates that appear.
- 5.
Click the Next button.
- 6.
Name the project Chapter20 and leave it in the same location.
- 7.
Click the Next button.
- 8.
Choose the framework to be used, which in our projects will be .NET 6.0 or higher.
- 9.
Click the Create button.
- 10.
Right-click the Chapter20 project in the Solution Explorer panel.
- 11.
Click the Set as Startup Project option.
- 12.
Right-click the Chapter20 project.
- 13.
Choose Add.
- 14.
Choose Item.
- 15.
Choose Class.
- 16.
Name the class Enumerations.cs.
- 17.
Amend the code to have a different namespace and have the Month enumeration within this namespace, as shown in Listing 20-1.
Declaring the enumeration in a different namespace
- 18.
Right-click the Program.cs file in the Solution Explorer window.
- 19.
Choose Rename.
- 20.
Change the name to MonthExample.cs.
- 21.
Press the Enter key.
- 22.
Double-click the MonthExample.cs file to open it in the editor window.
- 23.
Amend the code, as in Listing 20-2, to use the Enumerations namespace through the using statement on the first line, add the namespace for this class, and add the Main() method.
Declaring the enumeration and Main() method
Now we will investigate some of the methods from the System.Enum abstract class that we can use when working with enumerations.
Enumeration Methods
The GetNames(Type) method of the Enum class, which is used to return a String array with the names of the constants in the enumeration.
The GetName(Type, value) method of the Enum class, which is used to return the name of the constant in the enumeration with the specified value.
The ToString() method , which will convert the value of the enum instance to its equivalent string representation. This method may be an easier option than the GetName().
- 24.
Amend the code, as in Listing 20-3.
Set starting value of the enumeration, iterate, and display items
- 25.
Click the File menu.
- 26.
Choose Save All.
- 27.
Click the Debug menu.
- 28.
Choose Start Without Debugging.
![](https://imgdetail.ebookreading.net/2023/10/9781484286197/9781484286197__9781484286197__files__images__529949_1_En_20_Chapter__529949_1_En_20_Fig1_HTML.jpg)
A console of using iteration with hard-coded value. The Month enumeration is depicted.
Iterated items
- 29.
Press the Enter key to close the console window.
- 30.
Amend the code, as in Listing 20-4.
Using the enum length
- 31.
Click the File menu.
- 32.
Choose Save All.
- 33.
Click the Debug menu.
- 34.
Choose Start Without Debugging.
![](https://imgdetail.ebookreading.net/2023/10/9781484286197/9781484286197__9781484286197__files__images__529949_1_En_20_Chapter__529949_1_En_20_Fig2_HTML.jpg)
A console of using iteration based on the enum length from Get Names. The Month enumeration is depicted.
Iterated items using Enum.GetNames(typeof(Month)).Length
- 35.
Press the Enter key to close the console window.
Using the foreach Iteration
- 36.
Amend the code, as in Listing 20-5.
Foreach iteration
- 37.
Click the File menu.
- 38.
Choose Save All.
- 39.
Click the Debug menu.
- 40.
Choose Start Without Debugging.
![](https://imgdetail.ebookreading.net/2023/10/9781484286197/9781484286197__9781484286197__files__images__529949_1_En_20_Chapter__529949_1_En_20_Fig3_HTML.jpg)
A console with two types of iteration, one is based on the enum length from Get Names. The other iteration uses the foreach construct.
Iterated items using the foreach construct
- 41.
Press the Enter key to close the console window.
- 42.
Amend the code, as in Listing 20-6, to add a new iteration that uses the GetName() method.
Use the GetName() to find the constant name at a specific position
- 43.
Click the File menu.
- 44.
Choose Save All.
- 45.
Click the Debug menu.
- 46.
Choose Start Without Debugging.
![](https://imgdetail.ebookreading.net/2023/10/9781484286197/9781484286197__9781484286197__files__images__529949_1_En_20_Chapter__529949_1_En_20_Fig4_HTML.png)
A console window displays the list of the name of constants assigned at a particular value.
GetName() returns the name of the constant at a particular value
- 47.
Press the Enter key to close the console window.
Enumeration Values: GetValues()
- 48.
Amend the code, as in Listing 20-7.
Use the GetValues() to find the constant values
- 49.
Click the File menu.
- 50.
Choose Save All.
- 51.
Click the Debug menu.
- 52.
Choose Start Without Debugging.
![](https://imgdetail.ebookreading.net/2023/10/9781484286197/9781484286197__9781484286197__files__images__529949_1_En_20_Chapter__529949_1_En_20_Fig5_HTML.jpg)
A console depicts using the foreach iteration to display the month values. The array of integers is from 0 to 11.
GetValues() gives us the value of the constant
- 53.
Press the Enter key to close the console window.
Assigning Our Own Values to the Enumeration
- 54.
Amend the code, as in Listing 20-8.
In the Enumerations namespace, change the Apr constant
- 55.
Click the File menu.
- 56.
Choose Save All.
- 57.
Click the Debug menu.
- 58.
Choose Start Without Debugging.
![](https://imgdetail.ebookreading.net/2023/10/9781484286197/9781484286197__9781484286197__files__images__529949_1_En_20_Chapter__529949_1_En_20_Fig6_HTML.jpg)
A console depicts using the foreach iteration to display the month values. April has an assigned integer of 4, from this point on, other values are altered.
GetValues() gives us the value of the constant with April changed
- 59.
Press the Enter key to close the console window.
Use the GetName() and GetValues() Methods
- 60.
Amend the code, as in Listing 20-10, to use the GetValues() and GetName() methods.
GetName() and GetValues() methods
- 61.
Click the File menu.
- 62.
Choose Save All.
- 63.
Click the Debug menu.
- 64.
Choose Start Without Debugging.
![](https://imgdetail.ebookreading.net/2023/10/9781484286197/9781484286197__9781484286197__files__images__529949_1_En_20_Chapter__529949_1_En_20_Fig7_HTML.jpg)
A list of output from the Get Values and Get Name methods. The Get Value method returns an integer array, and the Get Name enumerates the month names.
GetName() and GetValues() methods
- 65.
Press the Enter key to close the console window.
Sample Application Using Enumerations
Five types of computer hardware
Three types of policy offered for computer hardware
Five factors required to calculate a quote (essentially 0, 1, 2, 3, 4, 5)
The enumerations are the constants that we will use in our code.
Hardware type
Policy type
Hardware value
The application will then calculate the monthly premium based on the formula
where the hardwareTypeFactor is obtained from the logic
Laptop is 5, Large_Screen is 5, Desktop is 4, Printer is 3, Small_Screen is 2
where the policyTypeFactor is obtained from the logic
Gold is 5, Silver is 3, Bronze is 2
where the hardwareValueFactor is obtained from the logic
Hardware value divided by 5000
Note
- 1.
Right-click the Chapter20 project.
- 2.
Choose Add.
- 3.
Choose Class.
- 4.
Name the class ComputerInsurance.cs.
- 5.
Click the Add button.
- 6.
Amend the code, as in Listing 20-11, to create a Main() method within the class and import the Enumerations namespace.
Three enumerations and a Main() method
- 7.
Amend the Enumerations.cs code, as in Listing 20-12, to create the additional enumerations we will be using.
Three additional enumerations
- 8.
Amend the ComputerInsurance class code to add the class-level variables as in Listing 20-13.
Add the required class-level variables
- 9.
Amend the class, as in Listing 20-14, to add the method, outside the Main() but inside the namespace, that will ask for user input.
Method that accepts user input
- 10.
Amend the class, as in Listing 20-15, to add the method that will calculate the hardware type factor.
Method that calculates the hardware type factor
- 11.
Amend the class, as in Listing 20-16, to add the method that will calculate the policy type factor.
Method that calculates the policy type factor
- 12.
Amend the class, as in Listing 20-17, to add the method that will calculate the hardware value factor.
Method that calculates the hardware value factor
- 13.
Amend the class, as in Listing 20-18, to add the method that will calculate the monthly premium.
Method that calculates the monthly premium
- 14.
Amend the code, as in Listing 20-19, to add the calls to the methods from within the Main() method and assign them to method-level variables.
Call the methods
- 15.
Right-click the Chapter20 project in the Solution Explorer panel.
- 16.
Choose Properties from the pop-up menu.
- 17.
Choose the ComputerInsurance class in the Startup object drop-down list.
- 18.
Close the Properties window.
- 19.
Click the File menu.
- 20.
Choose Save All.
- 21.
Click the Debug menu.
- 22.
Choose Start Without Debugging.
- 23.
Type 0, representing a Laptop, for the hardware type, as in Figure 20-8.
![](https://imgdetail.ebookreading.net/2023/10/9781484286197/9781484286197__9781484286197__files__images__529949_1_En_20_Chapter__529949_1_En_20_Fig8_HTML.jpg)
A sample menu with five enumeration values and their assigned hardware type. It depicts the user enters 0 for Laptop.
First menu – select Laptop by typing 0 as the enumeration value
- 24.
Press the Enter key to move to the next menu.
- 25.
Type 0, representing a Gold policy, for the policy type, as in Figure 20-9.
![](https://imgdetail.ebookreading.net/2023/10/9781484286197/9781484286197__9781484286197__files__images__529949_1_En_20_Chapter__529949_1_En_20_Fig9_HTML.jpg)
A sample menu with three enumeration values and their assigned policy type. It depicts the user enters 0 for Gold Policy.
Second menu – select Gold by typing 0 as the enumeration value
![](https://imgdetail.ebookreading.net/2023/10/9781484286197/9781484286197__9781484286197__files__images__529949_1_En_20_Chapter__529949_1_En_20_Fig10_HTML.jpg)
An input request prompts the user to enter an estimated value. The value 1000 is encoded.
Third entry for the hardware value
- 26.
Press the Enter key to move to the next input request.
- 27.
Type 1000 for the laptop value, as Figure 20-10, and press the Enter key.
![](https://imgdetail.ebookreading.net/2023/10/9781484286197/9781484286197__9781484286197__files__images__529949_1_En_20_Chapter__529949_1_En_20_Fig11_HTML.jpg)
A sample output for three enumerations, hardware type, policy type, and estimated value. The values are Laptop position 0, Gold position 0, and 5 dollars.
Output from sample application that uses three enumerations
- 28.
Press the Enter key to close the console window.
Are we sure this is the correct premium amount?
Laptop has a factor of 5.
Gold has a factor of 5.
1000 has a factor of 1000/5000 = 0.2.
MonthlyPremium is 5 X 5 x 0.2 = 5.00.
- 29.
Click the File menu.
- 30.
Choose Save All.
- 31.
Click the Debug menu.
- 32.
Choose Start Without Debugging.
- 33.
Type 4, representing a Small_Screen, for the hardware type
- 34.
Press the Enter key.
- 35.
Type 2, representing a Bronze policy, for the policy type .
- 36.
Press the Enter key.
- 37.
Type 100 for the screen value.
- 38.
Press the Enter key.
![](https://imgdetail.ebookreading.net/2023/10/9781484286197/9781484286197__9781484286197__files__images__529949_1_En_20_Chapter__529949_1_En_20_Fig12_HTML.jpg)
A sample output for three enumerations, hardware type, policy type, and estimated value. The two menus and three input requests are also depicted.
Output from sample application that uses three enumerations
Figure 20-12 shows the console window displaying the monthly premium for our chosen hardware type, policy type, and the estimated value.
Are we sure this is the correct premium amount?
Small_Screen has a factor of 2.
Bronze has a factor of 2.
100 has a factor of 100/5000 = .02.
MonthlyPremium is 2 X 2 x 0.02 = 0.08.
Figure 20-12 therefore does show the correct answer, so our code looks great.
- 39.
Amend the monthly premium method to add the new casting style to the display lines, as in Listing 20-20.
Casting style for conversion
- 40.
Click the File menu.
- 41.
Choose Save All.
- 42.
Click the Debug menu.
- 43.
Choose Start Without Debugging.
- 44.
Type 4, representing a Small_Screen, for the hardware type.
- 45.
Type 2, representing a Bronze policy, for the policy type.
- 46.
Type 100 for the screen value.
![](https://imgdetail.ebookreading.net/2023/10/9781484286197/9781484286197__9781484286197__files__images__529949_1_En_20_Chapter__529949_1_En_20_Fig13_HTML.jpg)
A series of text is framed on the console window. The text depicts the conversion using casting.
Output from the casting-style conversion
Figure 20-13 shows the console window displaying the monthly premium for our chosen hardware type, policy type, and the estimated value. It also confirms that the casting, (HardwareType)hardwareType and (PolicyType)policyType, has been successful.
Chapter Summary
So, finishing this chapter on enumerations, we can see that an enumeration is a value data type. We use an enumeration to declare constants with a descriptive name for the constants. In its basic form, an enumeration has a name, followed by a set of braces, which will contain a list of all the possible names. We use the enum keyword as a prefix to the enumeration name so that the compiler understands that the definition is an enumeration. By default, an enumeration will make the first item within the curly braces have a value 0, with each remaining value being incremented by 1. We can use the methods of the Enum abstract class to get the names and values of the constants, and we use GetName(), GetNames(), and GetValues() as well as the Length property.
Once again, another dive into an advanced feature of programming, which can be applied to our C# code helping make it more readable and easier to maintain. We should be immensely proud of our learning to date. In finishing this chapter, we have increased our knowledge further and we are advancing to our target.
![](https://imgdetail.ebookreading.net/2023/10/9781484286197/9781484286197__9781484286197__files__images__529949_1_En_20_Chapter__529949_1_En_20_Figa_HTML.jpg)
An illustration of concentric circles with two differently colored regions above a text that reads, Our target is getting closer.