Using Enumeration in C#
Objective
Many things in the real-world conceptually represent enumerations: the days of the week, months of the year, seasons, oceans, and compass directions, to name a few. In this tutorial we will show you how to use Enumeration in C# language.
Let's go
Definition of Enumeration
Enumeration (or just an enum for short), is very important in C# language. It mirrors the nature of the world in the programming language. See if you want to describe a week with all days of it, the easy way is to declare a enumeration with all days that belong to it.
- public enum Week
- {
- Sunday,
- Monday,
- Tuesday,
- Wednesday,
- Thursday,
- Friday,
- Saturday
- }
In the above code, we declare a enumeration named Week and seven fields in that enumeration, each is separated by a comma. You can write many of fields in the body of an enum with no restrict. When you want to refer to a field value in the enumeration, you just refer it directly from the enumeration name . Let see the example bellow:
- public void printDaysOfWeek(Week value_of_day)
- {
- switch(value_of_day){
- case Days.Monday:
- Console.WriteLine("This is Monday");
- break;
- case Days.Tuesday:
- Console.WriteLine("This is Tuesday");
- break;
- case Days.Wednesday:
- Console.WriteLine("This is Wednesday");
- break;
- case Days.Thursday:
- Console.WriteLine("This is Thursday");
- break;
- case Days.Friday:
- Console.WriteLine("This is Friday");
- break;
- case Days.Saturday:
- Console.WriteLine("This is Saturday");
- break;
- case Days.Sunday:
- Console.WriteLine("This is Sunday");
- break;
- default:
- Console.WriteLine("This is not a day");
- break;
- }
- }
Enumeration with Multiple Named Values
In Enumeration, you can declare multiple named with same value. The following snippet code declares two fileds named Wednesday and DupWednesday that have the same value.
- public enum WeekWithMultipleNamedValues
- {
- Sunday,
- Monday,
- Tuesday,
- Wednesday,
- DupWednesday = Wednesday,//the HumpDay field has same value with Wednesday
- Thursday,
- Friday,
- Saturday
- }
- public enum Week
- {
- Sunday = 0,
- Monday = 1,
- Tuesday = 2,
- Wednesday = 3,
- Thursday = 4,
- Friday = 5,
- Saturday = 6,
- }
Underlying Enumeration Types
By default, compiler makes the value type of each fields is int (integer) as a default type. If you want to change that default type, you can declare target type directly after the name of Enumeration. Note that you can only specify some types of enumeration include byte, short, int, long, sbyte, ushort, uint, or ulong. Bellow is an example of how to change default type:
- enum Week: byte
- {
- Sunday,
- Monday,
- Tuesday,
- Wednesday,
- Thursday,
- Friday,
- Saturday,
- }
Summary
In this tutorial we have show you about enumeration, includes:
- How to declare a enumeration
- Multiple named value in enumeration
- How to change type of enumeration
Add new comment
- 102 views