C# Enums
An enum
is a special “class” that represents a group of constants (unchangeable/read-only variables).
To create an enum
, use the enum
keyword (instead of class or interface), and separate the enum items with a comma:
Enum is short for “enumerations”, which means “specifically listed”.
Enum inside a Class
You can also have an enum
inside a class【可以在类里面定义 Enum】:
The output will be:
Enum Values
By default, the first item of an enum has the value 0, The second has the value 1, and so on. 【每个枚举的值】
To get the integer value from an item, you must explicitly convert the item to an int
:
The output will be:
You can also assign your own enum values, and the next items will update their numbers accordingly:
The output will be:
Enum in a Switch Statement
Enums are often used in switch
statements to check for corresponding values:
The output will be:
Why And When To Use Enums?
Use enums when you have values that you know aren’t going to change, like month days, days, colors, deck of cards, etc.