7.0 Enums
File Location
Right click on your solution
Go to Add > New Project and select Console App (.NET Framework)
Name it
Enums
Discussion
An enumeration is a set of named integer constants. An enumeration is declared using the enum keyword. C# enumerations contain their own values and cannot inherit or pass inheritance.
Visualization
class Program
{
// 1 2
enum Days
{
// 3
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday
}
}Declaring you are building an enum
Naming your enum
DaysInputting values to your enum
Declaration
When you declare an enum the syntax will look like this.
enum <enum_name>
{
enumeration list
}The enumeration list is a comma-separated list of identifiers. Each member of the list stands for an integer value and proceeds to add one integer value per index move. Such as 0, 1, 2, 3,...
So for this enumeration, Sun would stand for 0, Mon would stand for 1, Tue would stand for 2, and so on
class Program
{
enum Days
{
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday
}
static void Main(string[] args)
{
Days value = Days.Saturday;
if (value == Days.Saturday || value == Days.Sunday)
{
Console.WriteLine("It's the freakin weekend baby!");
}
if (value == Days.Friday)
{
Console.WriteLine("Friday is basically the weekend.");
}
else
{
Console.WriteLine("Have fun at work.");
}
Console.ReadLine();
}
}Above, we have a small program that has an enum of the days of the week. On the surface you would not be able to tell, but really your program is storing these values as integers. Starting with Sunday as 0 and ending with Saturday as 6. Then we have a simple if else statement demonstrating using those values.
Below is an example incorporating switch cases with an enum. It is helpful to set a breakpoint to follow how the program is communicating.
class Program
{
public enum G
{
None,
BoldFormat,
ItalicsFormat,
Hyperlink
};
public static bool IsFormat(G e)
{
switch (e)
{
case G.BoldFormat:
case G.ItalicsFormat:
{
return true;
}
default:
{
return false;
}
}
}
static void Main(string[] args)
{
G e1 = G.None;
if (IsFormat(e1))
{
Console.WriteLine("Error");
}
G e2 = G.ItalicsFormat;
if (IsFormat(e2))
{
Console.WriteLine("True");
}
Console.ReadLine();
}
}Our program starts at our
Main()method, hits the firstifstatement that says if theNonevalue in our enum is declared asIsFormat, then display an error message.Then, our program hits our
IsFormatswitch case and determines thatNoneis not an accepted format.Next, our program hits the second
ifstatement of ourMain()method that says ifItalicsFormat,e2, is an accepted format then print True.Then the program goes back to our
switchstatement, determines that the value is an accepted format and goes back to theifstatement to print True.
Challenge
Build an enum of different members of your family or friends and use if else statements combined with a switch case to display different information about them.
Next: Null
Last updated