Flags / bit fields as Enum in C#

C#

Please contribute by voting. Thanks!
2

Enum in C# is a powerful construct. And besides its standard use It can also be used as a bit field / flags. The purpose of a bitfield / flags is to be able to combine multiple Enum values compared to the common single-value usage of Enum.

Example of a standard use Enum:

public enum Gender
{
    Boy,
    Girl,
    Unknwon
}

public class Person
{
    public string FirstName = "Mary";
    public Gender Gender = Gender.Girl;
}

Note that the person only can have one gender.

Example of a bit field / flags Enum:

public enum Interests
{
    Football = 1,
    Dancing  = 2,
    Computers = 4,
    Horses = 8
}

public class Person
{
    public string FirstName = "John";
    public Interests Interests = Interests.Computers | Interests.Dancing;
}

Note that a person in this example can have multiple interests.

It's important that you define the values of a flags / bit field Enum as the power of two (2^1, 2^2, 2^3, 2^4 and so on...). Another difference from the first example is the [Flags]-attribute above the Enum definition, it enables a nice representation by the .ToString() method:

var john = new Person();
Console.WriteLine(john.Interests.ToString());
//Writes: Dancing, Computers

Article created: May 23. Edited May 24.

Your comment

You need to sign up / log in to comment this article

Author

Created by Faith Logan [4] May 23

Share article

Do you know about

Domain-driven Design (DDD)?

Write an article