C# Enum

Enumeration types

The enum keyword is used to declare an enumeration, a distinct type that consists of a set of named constants called the enumerator list.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public static class GenericStatus
{
public enum GenStatusEnum
{
Pending,
Approved,
Declined
}

public static string ReadStatus(int id)
{
GenStatus s;
Enum.TryParse<GenStatus>(id.ToString(), out s);
return s.ToString();
}
}

Enumeration types as bit flags

You can use an enumeration type to define bit flags

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using System;

namespace EnumDemo.Enum
{
[Flags]
public enum Days
{
None = 0,
Sunday = 1,
Monday = 2,
Tuesday = 4,
Wednesday = 8,
Thursday = 16,
Friday = 32,
Saturday = 64
}
}

You create a bit flags enum by applying the System.FlagsAttribute attribute and defining the values appropriately so that AND, OR, NOT and XOR bitwise operations can be performed on them.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
using EnumDemo.Enum;
using System;

namespace EnumDemo
{
class Program
{
static void Main(string[] args)
{
// Initialize with two flags using bitwise OR.
var meetingDays = Days.Tuesday | Days.Thursday | Days.Friday;
Console.WriteLine($"Meeting days are {meetingDays} with flag value {(int)meetingDays}");
// Meeting days are Tuesday, Thursday, Friday with flag value 52

// Toggle a flag using bitwise XOR, this will remove `Days.Tuesday` from `meetingDays`
meetingDays = meetingDays ^ Days.Tuesday;
Console.WriteLine($"Meeting days are {meetingDays} with flag value {(int)meetingDays}");
// Meeting days are Thursday, Friday with flag value 48

// Test value of flags using bitwise AND, this is checking for the existance of `Days.Thursday` in `meetingDays`
bool test = (meetingDays & Days.Thursday) == Days.Thursday;
Console.WriteLine($"Thursday {(test == true ? "is" : "is not")} a meeting day.");
// Thursday is a meeting day.
}
}
}