How to Use C# Enum Flag

2020/12/111 min read
bookmark this

A quick code snippet to show use enum flag by using the power of two. So you can define your enum and set the value as following, this will make the combine flag be unique.

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

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

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

Following are few way how 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 has type4");
		}

The bove code result will be the following.

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