Guide to the Language


Download 2 Mb.
Pdf ko'rish
bet50/78
Sana30.04.2023
Hajmi2 Mb.
#1414515
TuriGuide
1   ...   46   47   48   49   50   51   52   53   ...   78
Bog'liq
C sharp

CHAPTER 20
Enum
An enumeration is a special kind of value type consisting of a list of named 
constants. To create one, you use the enum keyword followed by a name 
and a code block containing a comma-separated list of constant elements.
enum State { Run, Wait, Stop };
This enumeration type can be used to create variables that can hold 
these constants. To assign a value to the enum variable, the elements are 
accessed from the enum as if they were static members of a class.
State s = State.Run;
 Enum Example
The switch statement provides a good example of when an enumeration 
can be useful. Compared to using ordinary constants, an enumeration 
has the advantage of allowing the programmer to clearly specify what 
constant values are allowed. This provides compile-time type safety, and 
IntelliSense also makes the values easier to remember.
switch (s)
{
case State.Run: break;
case State.Wait: break;
case State.Stop: break;
}


118
 Enum Constant Values
There is usually no need to know the actual constant values that the enum 
constants represent, but sometimes it can be useful. By default, the first 
element has the value 0, and each successive element has one value 
higher.
enum State
{
Run, // 0
Wait, // 1
Stop // 2
};
These default values can be overridden by assigning values to the 
constants. The values can be computed from an expression and they do 
not have to be unique.
enum State
{
Run = 0, Wait = 3, Stop = Wait + 1
};
 Enum Constant Type
The underlying type of the constant elements is implicitly specified as int, 
but this can be changed by using a colon after the enumeration’s name 
followed by the desired integer type.
enum MyEnum : byte {};
Chapter 20 enum


119

Download 2 Mb.

Do'stlaringiz bilan baham:
1   ...   46   47   48   49   50   51   52   53   ...   78




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling