[edit] Enumeration Basics
short data types can have values between -32,768 to 32,767. What if you wanted to declare your own values such as the days of the week. We will cover basic enumerations in this chapter.
Syntax
enum <TypeName>
{
value1,
value2,
...
valueX
}
assign the values above like this
VariableName = TypeName.value;
using System;
class Program
{
enum days
{
sunday, //Position 0
monday, //Position 1
tuesday, //Position 2
wednesday, //Position 3
thursday, //Position 4
friday, //Position 5
saturday, //Position 6
}
static void Main(string[] args)
{
days x; //Declare type days
x = days.sunday;
Console.WriteLine(x);
Console.Read();
}
}
Output
sunday
You cannot declare enumerations inside the main block because a enumeration cannot execute, its only a definition. So you must place it outside the main block as demonstrated above. Also, the positions are automatically assigned unless you initialize the position differently. We will discuss the below
[edit] Csharp Enumerations storage type
You can also define a storage type of an enumeration. Each value in an enumeration can accept a storage type which is int by default.
using System;
class Program
{
enum days : byte
{
sunday = 4, //Position 4
monday = 5, //Position 5
tuesday, //Position 6
wednesday, //Position 7
thursday, //Position 8
friday, //Position 9
saturday, //Position 10
}
static void Main(string[] args)
{
days x; //Declare type days
byte y;
x = days.friday; //x equals friday
y = (byte)days.friday; //y equals value position of friday
//explicit conversion required
Console.WriteLine(x);
Console.WriteLine(y);
Console.Read();
}
}
Output
friday
9
|