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
Declaring you are building an enum
Naming your enum
Days
Inputting values to your enum
Declaration
When you declare an enum the syntax will look like this.
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
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.
Our program starts at our
Main()
method, hits the firstif
statement that says if theNone
value in our enum is declared asIsFormat
, then display an error message.Then, our program hits our
IsFormat
switch case and determines thatNone
is not an accepted format.Next, our program hits the second
if
statement of ourMain()
method that says ifItalicsFormat
,e2
, is an accepted format then print True.Then the program goes back to our
switch
statement, determines that the value is an accepted format and goes back to theif
statement 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