C# Simplified, part 3 - Enumerations
(Page 6 of 6 )
Enumerations are a set of human readable names given instead of the numerical values. They derive from the System.Enum class.
Listing 3.10
case 1:
Console.WriteLine("YES");
break;
case 2:
Console.WriteLine("NO");
break;
Instead of specifying numerical values like 1 and 2 as in the above listing, you can use meaningful constants like ok and cancel. This can be achieved with the help of enumerations. They are defined by using the keyword enum as shown in the following code snippet:
enum Employees
{
YES,
NO
}
In the above code, an enumeration named Employees is defined with two constants YES and NO. Each constant has its own numerical values. By default, the numbering system starts from 0. However, you can change the order as shown in the code snippet given below:
enum Employees
{
YES = 10,
NO = 20
}
Note that the data type for each constant in an enumeration is an integer by default. But you can modify this behavior to byte, long, and so forth as shown in listing 3.11:
Listing 3.11
enum Employees : byte
{
YES,
NO
}
In listing 3.12, an enumeration named Employees is declared with three constants. A method named Display() is then created with the object of our enumerator. Inside the Main() method, an instance of the enumerator is created, and that instance is passed as a parameter to the Display() method. Since I have passed the Counsellors constant, the statements relevant to them will be printed as final output. You may notice from the code that the case clause looks more meaningful and readable than numerical references.
Listing 3.12 using System;
enum Employees
{
Instructors,
Assistants,
Counsellors
}
class EnumDemo
{
public static void Display(Employees e)
{
switch(e)
{
case Employees.Instructors:
Console.WriteLine("You are an Instructor");
break;
case Employees.Assistants:
Console.WriteLine("You are one of the Assistants");
break;
case Employees.Counsellors:
Console.WriteLine("You are a counsellor");
break;
default:break;
}
}
public static void Main(String[] args)
{
Employees emp;
emp = Employees.Counsellors;
Display(emp);
}
}
Summary
In this article, you have learned about different escape characters and format specifiers with the help of complete source codes and screenshots. The article also discussed two important topics -- arrays and enumerations -- with the help of source code.
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |