How to Use C# Enum Flag

2020/12/112 min read
bookmark this
Responsive image

Table of Contents

  1. Introduction
  2. Define Enum with Power of Two
  3. Define Enum with Bit Shift
  4. Using the Enum Flags
  5. Conclusion

Introduction

A quick code snippet to show how to use enum flags by using the power of two. You can define your enum and set the values as follows. This will make the combined flag values unique.

Define Enum with Power of Two

public enum MyType : uint {
		Undefined = 0,
		Type1 = 1,
		Type2 = 2,
		Type3 = 4,
		Type4 = 8,
		Type5 = 16
	}

Define Enum with Bit Shift

Or you can use the bit shift if you don't want to count the numbers.

public enum MyType2 : uint {
		Undefined = 0,
		Type1 = 1,
		Type2 = 2 << 0,
		Type3 = 2 << 1,
		Type4 = 2 << 2,
		Type5 = 2 << 3
	}

Using the Enum Flags

Following are a few ways to use this enum.

// set value
		var myvalue = MyType.Type1 | MyType.Type2;
		Console.WriteLine(myvalue);

		var myvalue2 = MyType2.Type1 | MyType2.Type2;
		Console.WriteLine(myvalue2);

		// check value
		if ((myvalue2 & MyType2.Type1) == MyType2.Type1) {
			Console.WriteLine("myvalue2 has Type1");
		}

		// check value
		if ((myvalue2 & MyType2.Type4) != MyType2.Type4) {
			Console.WriteLine("myvalue2 doesn't have type4");
		}

The above code result will be the following:

3 3 myvalue2 has Type1 myvalue2 doesn't have type4 myvalue2 has type4? False

Conclusion

Using the [Flags] attribute and the power of two for enum values allows you to combine multiple enum values into a single variable and check for specific flags using bitwise operations.