C# Enums Tutorial with Examples
1. What is C# Enum
No ADS
The enum in C # is a keyword, which is used to declare an enumeration.
Now we need to see, if there is no Enum in some situations. For example, you need a list that contains days of the week. Usually you define 7 constants, to represent 7 days in the week.
WeekDayConstants.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CSharpEnumTutorial
{
class WeekDayConstants
{
public const int MONDAY = 2;
public const int TUESDAY = 3;
public const int WEDNESDAY = 4;
public const int THURSDAY = 5;
public const int FRIDAY = 6;
public const int SATURDAY = 7;
public const int SUNDAY = 1;
}
}
A class with a method returns the job todo in each specific day of week. (Similar to the timetable).
Timetable.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CSharpEnumTutorial
{
class Timetable
{
// Returns name of Job will do
public static String getJob(int dayInWeek)
{
if (dayInWeek == WeekDayConstants.SATURDAY
|| dayInWeek == WeekDayConstants.SUNDAY)
{
return "Nothing";
}
return "Coding";
}
}
}
It is obvious that such code lines are not safe. For example, you call Timetable.getJob(int) function, but the input parameter does not belong to a defined set.
- No Type-Safety: First of all it’s not type-safe; you can assign any valid int value to dayInWeek
- No Meaningful Printing: printing value of any of these constant will print its numeric value instead of meaningful name of day e.g. when you print MONDAY it will print "2" instead of "MONDAY"
And here's how to use enum to define days of the week.
WeekDay.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CSharpEnumTutorial
{
public enum WeekDay
{
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
}
And example using Weekday enum:
Timetable2.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CSharpEnumTutorial
{
class Timetable2
{
public static String getJob(WeekDay weekDay)
{
if (weekDay == WeekDay.SATURDAY || weekDay == WeekDay.SUNDAY)
{
return "Nothing";
}
return "Coding";
}
}
}
2. Can use the == operator to compare the elements of enum
No ADS
Enum is a reference object like a class, interface, but it can also use the == operation
Let see how reference objects are compared.
// To compare the reference object, generally used method equals(..)
object obj1 = ...;
// Comparing object with null, can use the == operator
if (obj1 == null)
{
}
object obj2 = ...;
// Not null
if (obj1 != null)
{
// Comparing two objects.
if (obj1.Equals(obj2))
{
}
}
With Enum, you can use the == operator to compare.
CompareEnumDemo.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CSharpEnumTutorial
{
class CompareEnumDemo
{
public static void Main(string[] args)
{
WeekDay today = WeekDay.SUNDAY;
// Use the == operator to compare two elements of Enum
if (today == WeekDay.SUNDAY)
{
Console.WriteLine("Today is Sunday");
}
Console.Read();
}
}
}
3. Fetch on the elements of Enum
We can fetch on all elements of Enum. See examples:
ValuesDemo.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CSharpEnumTutorial
{
class ValuesDemo
{
public static void Main(string[] args)
{
// Get all the elements of the Enum.
Array allDays = Enum.GetValues(typeof(WeekDay));
foreach (WeekDay day in allDays)
{
Console.WriteLine("Day: " + day);
}
Console.Read();
}
}
}
Results of running the example:
Day: MONDAY
Day: TUESDAY
Day: WEDNESDAY
Day: THURSDAY
Day: FRIDAY
Day: SATURDAY
Day: SUNDAY
4. Enum with Attribute
No ADS
You can attach the Attribute to the elements of Enum, which helps Enum to bring more information , and you can get that information out to each element of Enum.
See more:
- Hướng dẫn và ví dụ C# Attribute
GenderAttr.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CSharpEnumTutorial
{
class GenderAttr : Attribute
{
// code: M, text = Male
// code: F, text = Female
internal GenderAttr(string code, string text)
{
this.Code = code;
this.Text = text;
}
public string Code { get; private set; }
public string Text { get; private set; }
}
}
Gender enum has two elements MALE and FEMALE.
Gender.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CSharpEnumTutorial
{
public enum Gender
{
// A element of Enum, has attribute
[GenderAttr("M","Male")]
MALE,
// A element of Enum, has attribute
[GenderAttr("F","Female")]
FEMALE
}
}
Genders.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
namespace CSharpEnumTutorial
{
class Genders
{
// Returns Gender corresponding to the code.
// (This method may returns null)
public static Gender? GetGenderByCode(string code)
{
// Get all the elements of the Enum.
Array allGenders = Enum.GetValues(typeof(Gender));
foreach (Gender gender in allGenders)
{
string c = GetCode(gender);
if (c == code)
{
return gender;
}
}
return null;
}
public static string GetText(Gender gender)
{
GenderAttr genderAttr = GetAttr(gender);
return genderAttr.Text;
}
public static string GetCode(Gender gender)
{
GenderAttr genderAttr = GetAttr(gender);
return genderAttr.Code;
}
private static GenderAttr GetAttr(Gender gender)
{
MemberInfo memberInfo = GetMemberInfo(gender);
return (GenderAttr)Attribute.GetCustomAttribute(memberInfo, typeof(GenderAttr));
}
private static MemberInfo GetMemberInfo(Gender gender)
{
MemberInfo memberInfo
= typeof(Gender).GetField(Enum.GetName(typeof(Gender), gender));
return memberInfo;
}
}
}
And example using Gender enum:
GenderTest.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CSharpEnumTutorial
{
class GenderTest
{
public static void Main(string[] args)
{
Gender marryGender = Gender.FEMALE;
Console.WriteLine("marryGender: " + marryGender);
Console.WriteLine("Code: " + Genders.GetCode(marryGender)); // F
Console.WriteLine("Text: " + Genders.GetText(marryGender)); // Femate
String code = "M";
Console.WriteLine("Code: " + code);
// Phương thức có thể trả về null.
Gender? gender = Genders.GetGenderByCode(code);
Console.WriteLine("Gender by code: " + gender);
Console.Read();
}
}
}
Running the example:
marryGender: FEMALE
Code: F
Text: Female
Code: M
Gender by code: MALE
5. Methods in enum?
In C # enum can not have methods, but in case you want to have something like Enum and have methods you can define a class, this class does not allow to create objects in addition the object it was made available.
GenderX.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CSharpEnumTutorial
{
class GenderX
{
public static readonly GenderX MALE = new GenderX("M","Male");
public static readonly GenderX FEMALE = new GenderX("F","Female");
private string code;
private string text;
// Private Constructor: Do not allow creating objects from outside class.
private GenderX(string code, string text)
{
this.code = code;
this.text = text;
}
public string GetCode()
{
return this.code;
}
public string GetText()
{
return this.text;
}
public static GenderX GetGenderByCode(string code)
{
if (MALE.code.Equals(code))
{
return MALE;
}
else if (FEMALE.code.Equals(code))
{
return FEMALE;
}
return null;
}
}
}
No ADS
C# Programming Tutorials
- Inheritance and polymorphism in C#
- What is needed to get started with C#?
- Quick learning C# for Beginners
- Install Visual Studio 2013 on Windows
- Abstract class and Interface in C#
- Install Visual Studio 2015 on Windows
- Compression and decompression in C#
- C# Multithreading Programming Tutorial with Examples
- C# Delegates and Events Tutorial with Examples
- Install AnkhSVN on Windows
- C# Programming for Team using Visual Studio and SVN
- Install .Net Framework
- Access Modifier in C#
- C# String and StringBuilder Tutorial with Examples
- C# Properties Tutorial with Examples
- C# Enums Tutorial with Examples
- C# Structures Tutorial with Examples
- C# Generics Tutorial with Examples
- C# Exception Handling Tutorial with Examples
- C# Date Time Tutorial with Examples
- Manipulating files and directories in C#
- C# Streams tutorial - binary streams in C#
- C# Regular Expressions Tutorial with Examples
- Connect to SQL Server Database in C#
- Work with SQL Server database in C#
- Connect to MySQL database in C#
- Work with MySQL database in C#
- Connect to Oracle Database in C# without Oracle Client
- Work with Oracle database in C#
Show More