Zum Hauptinhalt springen
tsecurity.de LIVE
Echtzeit-Radar & Feeds
Alle RSS Feeds
👥 Community & Social
YouTube Security VideosAndroid Police: Samsung is smashing records! #shorts #tech #phones(21.09.2026 um 13:55 Uhr)
YouTube Security Videosheise & c't: Bundesnetzagentur wollte diesen Futterautomaten verbieten(21.09.2026 um 13:53 Uhr)
YouTube Security VideosNeil Patel: Your Google Traffic Isn't An Asset It's A Loan #shorts(21.09.2026 um 14:05 Uhr)
Windows Tipps & SecurityF-14 A Tomcat Top Gun endlich als Revell Klemmbausteinmodell erhältlich(21.09.2026 um 14:27 Uhr)
Sichere ProgrammierungShow the Hand-Back Sample Before Approving an Agent Score(21.09.2026 um 14:15 Uhr)
Sichere ProgrammierungHybrid retrieval in one Postgres query: RRF over tsvector + pgvector(21.09.2026 um 14:15 Uhr)
YouTube Security VideosAndroid Police: Samsung is smashing records! #shorts #tech #phones(21.09.2026 um 13:55 Uhr)
YouTube Security Videosheise & c't: Bundesnetzagentur wollte diesen Futterautomaten verbieten(21.09.2026 um 13:53 Uhr)
YouTube Security VideosNeil Patel: Your Google Traffic Isn't An Asset It's A Loan #shorts(21.09.2026 um 14:05 Uhr)
Windows Tipps & SecurityF-14 A Tomcat Top Gun endlich als Revell Klemmbausteinmodell erhältlich(21.09.2026 um 14:27 Uhr)
Sichere ProgrammierungShow the Hand-Back Sample Before Approving an Agent Score(21.09.2026 um 14:15 Uhr)
Sichere ProgrammierungHybrid retrieval in one Postgres query: RRF over tsvector + pgvector(21.09.2026 um 14:15 Uhr)
Intelligence View
⚡ tsecurity.de Intelligence

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…

0
↗ Quelle (dev.to)
Reagiere als Erste:r — dein Feedback zählt!

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
}






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
}









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;
}
}






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
}
}









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









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
}
}








  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}");
}









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
}
}








  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!
}
}









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
}
}






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.

Ähnliche Beiträge
🔍 Verwandte News

Auch interessante Nachrichten Mastering C# Fundamentals: Enumerations

Thematisch verwandte Begriffe: Mastering, Fundamentals, Enumerations · 6 Treffer

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Zum Aktualisieren ziehen
ZERO-DAY CVE-2026-94097 | A vulnerability was determined in Netcore NBR200V2 1.3.241127.071246. Th…
Advisory →
TTS Reader • tsecurity.de Voice
tsecurity.de Icon
tsecurity.de App
Offline-Lesen, Eilmeldungen & 0ms Ladezeit

Installiere tsecurity.de direkt auf deinen Home-Bildschirm für das ultimative Vollbild-Magazinerlebnis ohne Browser-Leisten.

Nächster Beitrag
Themen-Radar & Intelligence Matrix
Echtzeit-Taxonomie nach Angriffsvektoren & Plattformen

tsecurity.de Live Threat Radar

🔴 LIVE RADAR
MONITORING
AKTIV
CVE-DATENBANK
LIVE
🔍
Community Radar & Live Chat
Sentinel Bot online • Live-Stream
Dein Cluster: Security Explorer
Match:
lädt…
Verbindung zum Community-Stream wird aufgebaut...
Bearbeitungsmodus — Senden überschreibt deine Nachricht
Community-Puls — was gerade passiert
lädt…
Aktivitäten deiner Analysten
lädt…
Neues Thema oder Eilmeldung einreichen

Reiche interessante Links, Zero-Days oder Debatten ein. Die Community entscheidet per Upvote über die Veröffentlichung.

Heiß diskutierte Einreichungen
🔖 Gespeicherte Artikel
📂 Keine gespeicherten Artikel vorhanden.
Zurück Ziehen Vor
Links: vorheriger Artikel Rechts: nächster Artikel unten: schließen
News NIS-2 Frühwarnung Tier-1 Intel ⏱️ 3 Min vor 10 Min
Artikeldaten werden geladen...

Zurück: vorheriger Vor: nächster
↗ Original-Quelle
Social Reaktionen Deine Reaktion zählt
Einstufung & Relevanz-Poll 0 Stimmen
In sozialen Netzwerken teilen 1-Klick