...

/

Storing Values Using Different Techniques

Storing Values Using Different Techniques

Learn how to efficiently store and manage data using enum types and collections for multiple values.

Let’s dive into C# enum types, which efficiently store values. We’ll work with the enum and collection, showcasing how it simplifies data storage. We’ll also explore bucket lists, all while keeping code concise and efficient.

Storing a value using an enum type

Sometimes, a value needs to be one of a limited set of options. For example, there are seven ancient wonders of the world, and a person may have one favorite. At other times, a value must be a combination of a limited set of options. For example, a person may have a bucket list of ancient world wonders they want to visit. We can store this data by defining an enum type.

An enum type is a very efficient way of storing one or more choices because, internally, it uses integer values in combination with a lookup table of string descriptions:

Step 1: Add a new file to the PacktLibraryNetStandard2 project named WondersOfTheAncientWorld.cs.

Step 2: Modify the WondersOfTheAncientWorld.cs file, as shown in the following code:

Press + to interact
namespace Packt.Shared;
public enum WondersOfTheAncientWorld
{
GreatPyramidOfGiza,
HangingGardensOfBabylon,
StatueOfZeusAtOlympia,
TempleOfArtemisAtEphesus,
MausoleumAtHalicarnassus,
ColossusOfRhodes,
LighthouseOfAlexandria
}

Note: If we are writing code in a .NET Interactive notebook, then the code cell containing the enum must be above the code cell defining the Person class.

Step 3: In Person.cs, add the following statement to our list of fields:

Press + to interact
public WondersOfTheAncientWorld FavoriteAncientWonder;

Step 4: In Program.cs, add the following statements:

Press + to interact
bob.FavoriteAncientWonder =
WondersOfTheAncientWorld.StatueOfZeusAtOlympia;
WriteLine(
format: "{0}'s favorite wonder is {1}. Its integer is {2}.",
arg0: bob.Name,
arg1: bob.FavoriteAncientWonder,
arg2: (int)bob.FavoriteAncientWonder);

Step 5: Run the code and view the result, as shown in the following output:

Bob Smith's favorite wonder is StatueOfZeusAtOlympia. Its integer is 2.

The enum value is internally stored as an int for efficiency. The int values are automatically assigned starting at 00 ...