How do enums work in C#

Enums in C# are a special "value type" that allows you to define a set of named constants. Enums make your code more readable and manageable by grouping related constants under a single type. This is especially useful for representing states, options, or categories.

When you declare an enum, you can also specify the underlying integral type that will store the enum values. By default, C# uses int as the underlying type for enums. Each item in the enum is assigned an integer value starting from 0, unless specified otherwise.

Here’s a simple example of defining and using an enum in C#:

// Define an enum for the days of the week public enum DayOfWeek { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday } // Using the enum class Program { static void Main(string[] args) { DayOfWeek today = DayOfWeek.Monday; Console.WriteLine($"Today is {today}"); } }

C# enums value type named constants programming constants readability code management DayOfWeek