- What is Enumeration in C#?
- What is the advantage of using enumeration in C#?
- How to use enumeration in C# programming?
Enumeration provides an efficient way to assign multiple constant integral values to a single variable. Enumeration improves code clarity and makes the program easier to maintain. The enumeration in C# also provides more security by better error-checking technology and compiler warnings.
An enumeration can be defined using enum keyword. In enumeration, you can define a special set of value that can be assigned with enumeration. For Example, you are creating an attendance log application in which a variable can contains value only Monday to Friday. The other value will not be applied to variables. In order to fulfill this requirement, you need to use enumeration that will hold only assigned values and will return the numeric position of values starting with zero.
Programming Example of Enumeration (C#)
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Enumeration { // creating enumeration for storing day. public enum attandance { Monday, Tuesday, Wednesday, Thursday, Friday } class Program { static void Main(string[] args) { attandance present = attandance.Monday;//Valid Console.WriteLine(present); //attandance absent = attandance.Sunday;//Invalid Console.ReadLine(); } } }
Output
Monday
__
In the preceding example, we created attendance enumeration in which 5 values are assigned as Monday, Tuesday, Wednesday, Thursday and Friday. Only these 5 values are valid entry for attendance enumeration variable. If you assign other entry as Sunday or Saturday, it will be invalid and you will get compile time error in C# programming.
Summary
In this chapter you learned what enumeration is and how to use it in C# programming. In next chapter you will learn about Structure in C#.