C# Enumerations Part 2


This entry is part 4 of 8 in the series C# Complex Types

Here are some examples of use cases for enumerations. Suppose you have a series of integer values that represent points or scores for some different levels of achievement. You want to be able to use the word instead of the value because this would be a lot easier to read and debug in your code. You could create an enumeration for this. Another way of saying this is that the enum is used to give a name to each constant so that the constant integer can be referred using its name.

Another example of the use of enumerations is having a list of importance values. You might have a list that goes from trivial to critical where trivial gets a value of one and critical gets a value of 5. Similarly you might have a list of priority values that have integer values attached to a to do list of tasks.

You may have a fixed set of values in a list, such as north, south, east and west as shown in the previous post.

In mathematics, cardinality refers to the number of elements in a set. In our directions example, the cardinality would be four. In the world of databases, cardinality refers to the “uniqueness” of the data. High cardinality means that the column contains a large percentage of totally unique values. Low cardinality means that the column contains a lot of “repeats” in its data range.

You can cast an int to an enum, and you can cast an (int-based) enum back to an int.

Here’s an enumumeration to keep track of the scores for tricks at a dog competition:

using System;
namespace EnumsHeadFirst
{   // code in Beginning C# 6 book - Ch 05 folder
    // keep track of the scores for tricks
    // at a dog competition - CODE IS MODIFIED.
    public enum TrickScore
    {
        Sit = 7, Beg = 25, RollOver = 50,
        Fetch = 10, ComeHere = 5, Speak = 30,
    }
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(TrickScore.RollOver);// output: Rollover
            int myInt = (int)TrickScore.Fetch * 3;
            Console.WriteLine(myInt); // output: 30

            // int -> TrickScore (which is a string):
            TrickScore myScore = (TrickScore)myInt;
            Console.WriteLine(myScore); // output: Speak
                                       
            string trick = "ComeHere";
            Enum.TryParse(trick, out TrickScore myVar);
            Console.WriteLine(myVar);  // output: ComeHere
            Console.WriteLine((int)myVar);  // output: 5
        }
    }
}

In the last few lines of the code above we were able to convert a string to an enum. We converted “ComeHere” to 5.

Series Navigation<< C# EnumerationsC# Structs Introduction >>