C# Enum
In C#, an enum (short for "enumeration") is used to define a set of named constants. Enumerations are useful for creating named values that can be used throughout your code and provide readability and type safety. In this tutorial, we'll discuss how to define and use enums in C#.
Syntax
The syntax for defining an enum in C# is as follows:
enum MyEnum {
Value1,
Value2,
Value3
}
Each named value in the enum is separated by a comma. By default, the underlying type of the enum is int, but it can be changed to any integral type.
Example
Let's say we want to define an enum called "DaysOfWeek" that represents the days of the week. Here's how we can implement it:
enum DaysOfWeek {
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
}
Now, we can use the enum in our code:
DaysOfWeek today = DaysOfWeek.Monday;
Console.WriteLine(today); // Output: Monday
Output
When we run the example code above, the output will be:
Monday
This is because we assigned the value "Monday" to the "today" variable, which was then printed to the console.
Explanation
In the example above, we defined an enum called "DaysOfWeek" that represents the days of the week. We then used the enum in our code by assigning the value "Monday" to a variable called "today" and printing it to the console.
Use
Enums are useful for creating named values that can be used throughout your code, providing readability and type safety. You can use enums to improve the readability of your code, as well as to make it less prone to errors.
Important Points
- The values of an enum start at 0 and increase by 1 for each named value.
- You can assign a specific value to a named value in the enum by specifying it after the value name (e.g. Value1 = 10).
- The type of an enum can be any integral type, but by default, it is int.
Summary
In this tutorial, we discussed how to define and use enums in C#. We covered the syntax, example, output, explanation, use, and important points of enums in C#. With this knowledge, you can now use enums in your C# code to create named values that provide readability and type safety throughout your application.