DEV Community

mohamed Tayel
mohamed Tayel

Posted on

Mastering C# Fundamentals: Enumerations

Meta Description: Learn how to create and use enumerations (enums) in C#. Understand the benefits of using enums for cleaner, more readable code, and see practical examples of how to implement them in different scenarios. Includes assignments to reinforce learning at easy, medium, and difficult levels

In C#, we've already learned how to create classes, but there are other custom types that we can leverage to enhance code clarity. One of these is called an enumeration. Let's dive into what an enumeration is, how to create it, and the best ways to use it effectively.

What is an Enumeration?

An enumeration (enum) is a distinct type consisting of a set of named constants. Enums are particularly helpful when you have a set of related named values. Instead of relying on arbitrary numeric values, you can use named values to make the code more readable and maintainable.

For instance, suppose you have a game with different levels of difficulty represented by numbers (1, 2, 3). Later, it may not be clear what 1 represents without a comment or context. Instead, an enumeration allows you to assign meaningful names, like Easy, Medium, and Hard.

Creating an Enumeration in C#

Enumerations are created using the enum keyword, followed by the enumeration name and a list of its members. Here’s an example of a DifficultyLevel enum:

enum DifficultyLevel
{
    Easy,        // Default value is 0
    Medium,      // Default value is 1
    Hard,        // Default value is 2
    Expert       // Default value is 3
}
Enter fullscreen mode Exit fullscreen mode

By default, Easy is assigned 0, Medium is assigned 1, and so on. You can also specify your own values:

enum DifficultyLevel
{
    Easy = 10,
    Medium = 20,
    Hard = 30,
    Expert = 40
}
Enter fullscreen mode Exit fullscreen mode

Using Enumerations in Code

Let’s see how we can use the DifficultyLevel enumeration in our Game class:

class Game
{
    public string Name { get; set; }
    public DifficultyLevel Level { get; set; }

    public Game(string name, DifficultyLevel level)
    {
        Name = name;
        Level = level;
    }

    public void DisplayInfo()
    {
        Console.WriteLine($"Game: {Name}, Difficulty Level: {Level}");
    }

    public void SetDifficulty(DifficultyLevel level)
    {
        Level = level;
    }
}
Enter fullscreen mode Exit fullscreen mode

Here, DifficultyLevel is used as a property in the Game class. This way, we know exactly which difficulty level is being set for the game without having to guess based on numbers.

Example Usage in Main Program

Now, let’s create some games and see how the enumeration helps us:

class Program
{
    static void Main()
    {
        Game chess = new Game("Chess", DifficultyLevel.Hard);
        Game sudoku = new Game("Sudoku", DifficultyLevel.Easy);

        chess.DisplayInfo();  // Output: Game: Chess, Difficulty Level: Hard
        sudoku.DisplayInfo(); // Output: Game: Sudoku, Difficulty Level: Easy

        // Change the difficulty level of Sudoku
        sudoku.SetDifficulty(DifficultyLevel.Medium);
        sudoku.DisplayInfo(); // Output: Game: Sudoku, Difficulty Level: Medium
    }
}
Enter fullscreen mode Exit fullscreen mode

Understanding Enumeration Behind the Scenes

In C#, enumerations are essentially integers. By default, the first value is 0 and each subsequent value increments by 1. You can also access the underlying integer value:

int hardValue = (int)DifficultyLevel.Hard;
Console.WriteLine(hardValue);  // Output: 2
Enter fullscreen mode Exit fullscreen mode

Assignments

Let’s put your understanding into practice with different levels of assignments.

Level 1: Easy

  1. Create an Enumeration for Seasons Create an enumeration named Season with values Spring, Summer, Autumn, and Winter. Write a console application that prints each season.
   enum Season
   {
       Spring,
       Summer,
       Autumn,
       Winter
   }

   class Program
   {
       static void Main()
       {
           Season currentSeason = Season.Winter;
           Console.WriteLine($"Current Season: {currentSeason}");  // Output: Current Season: Winter
       }
   }
Enter fullscreen mode Exit fullscreen mode
  1. Print Enumeration Values and Corresponding Integers Write a loop that prints the name and corresponding integer value for each Season.
   foreach (Season season in Enum.GetValues(typeof(Season)))
   {
       Console.WriteLine($"{season} = {(int)season}");
   }
Enter fullscreen mode Exit fullscreen mode

Level 2: Medium

  1. Create a Class Using an Enumeration for Car Types Create a class named Car with properties Model, Brand, and CarType. Use an enumeration for CarType (Sedan, SUV, Truck, Coupe). Write methods to display the car's details.
   enum CarType
   {
       Sedan,
       SUV,
       Truck,
       Coupe
   }

   class Car
   {
       public string Model { get; set; }
       public string Brand { get; set; }
       public CarType Type { get; set; }

       public Car(string model, string brand, CarType type)
       {
           Model = model;
           Brand = brand;
           Type = type;
       }

       public void DisplayCarDetails()
       {
           Console.WriteLine($"Model: {Model}, Brand: {Brand}, Type: {Type}");
       }
   }

   class Program
   {
       static void Main()
       {
           Car myCar = new Car("Model X", "Tesla", CarType.SUV);
           myCar.DisplayCarDetails();  // Output: Model: Model X, Brand: Tesla, Type: SUV
       }
   }
Enter fullscreen mode Exit fullscreen mode
  1. Use Enumeration to Control Game Level Logic Modify the Game class to use different messages for different difficulty levels. Print different encouragement messages for each level of difficulty.
   class Game
   {
       public string Name { get; set; }
       public DifficultyLevel Level { get; set; }

       public Game(string name, DifficultyLevel level)
       {
           Name = name;
           Level = level;
       }

       public void DisplayEncouragementMessage()
       {
           switch (Level)
           {
               case DifficultyLevel.Easy:
                   Console.WriteLine("You got this! Keep going!");
                   break;
               case DifficultyLevel.Medium:
                   Console.WriteLine("Challenge yourself, you can do it!");
                   break;
               case DifficultyLevel.Hard:
                   Console.WriteLine("Only the determined will succeed!");
                   break;
               case DifficultyLevel.Expert:
                   Console.WriteLine("You are on an expert level, good luck!");
                   break;
           }
       }
   }

   class Program
   {
       static void Main()
       {
           Game ticTacToe = new Game("Tic Tac Toe", DifficultyLevel.Medium);
           ticTacToe.DisplayEncouragementMessage();  // Output: Challenge yourself, you can do it!
       }
   }
Enter fullscreen mode Exit fullscreen mode

Level 3: Difficult

  1. Complex Scenario with Multiple Enumerations and Logic for Meal Planning Create a program for managing meal planning. Use two enumerations: MealType (Breakfast, Lunch, Dinner, Snack) and DietType (Vegan, Vegetarian, Keto, Paleo). Create a class Meal that includes both enumerations, and write methods that recommend different meals based on the type of diet and meal.
   enum MealType
   {
       Breakfast,
       Lunch,
       Dinner,
       Snack
   }

   enum DietType
   {
       Vegan,
       Vegetarian,
       Keto,
       Paleo
   }

   class Meal
   {
       public MealType MealTime { get; set; }
       public DietType Diet { get; set; }

       public Meal(MealType mealTime, DietType diet)
       {
           MealTime = mealTime;
           Diet = diet;
       }

       public void RecommendMeal()
       {
           if (Diet == DietType.Vegan)
           {
               if (MealTime == MealType.Breakfast)
               {
                   Console.WriteLine("Recommended Vegan Breakfast: Smoothie Bowl with Fresh Fruits");
               }
               else if (MealTime == MealType.Dinner)
               {
                   Console.WriteLine("Recommended Vegan Dinner: Grilled Vegetables with Quinoa");
               }
           }
           else if (Diet == DietType.Keto)
           {
               if (MealTime == MealType.Lunch)
               {
                   Console.WriteLine("Recommended Keto Lunch: Avocado Salad with Chicken");
               }
               else if (MealTime == MealType.Snack)
               {
                   Console.WriteLine("Recommended Keto Snack: Cheese and Nuts");
               }
           }
           // You can add more conditions for other DietTypes and MealTimes...
       }
   }

   class Program
   {
       static void Main()
       {
           Meal mealPlan = new Meal(MealType.Lunch, DietType.Keto);
           mealPlan.RecommendMeal();  // Output: Recommended Keto Lunch: Avocado Salad with Chicken
       }
   }
Enter fullscreen mode Exit fullscreen mode

This complex example shows how enumerations can make meal planning logic more organized and easy to understand by giving meaningful names to combinations of meal types and diets.


Conclusion

Enumerations in C# are an excellent way to represent sets of named constants, making code easier to understand and maintain. They help avoid "magic numbers" in your code and improve readability. Pract

icing these exercises will help you master defining, using, and getting creative with enumerations.

Top comments (0)