Net-informations.com

# Enum Flags Explained

## Enum

An Enum (Enumeration) type provides an efficient way to define a set of named integral constants that may be assigned to a variable.

## Enum Flags Attribute

The idea of Enum Flags is to take an enumeration variable and allow it hold multiple values. It should be used whenever the enum represents a collection of flags, rather than representing a single value. Such enumeration collections are usually manipulated using bitwise operators. 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.

#### VB.Net

You can use like this:

In conditions:

To properly implement an enum as a flag, you need to have the values increasing by a power of two (2). You should define enumeration constants in powers of two, that is, 1, 2, 4, 8, and so on. It is important, because it allows us to do bit-wise operations on the number. The values themselves can easily be calculated by raising 2 to the power of a zero-based sequence of numbers like the following:

yields this (yes, 2 to the zero power is one):

1, 2, 4, 8, 16, 32, 64

This means the individual flags in combined enumeration constants do not overlap.

Unlike the old enums, the actual values in a flags enumerator must be in sequence for it to work correctly. This does not refer to a base 10 sequence, but instead to a base 2 sequence. Hence the Character enumeration can now act in Bitwise Operators. The values of the Enum will look like the following:

What it is explain that the integer value expressed as base 2 must be as shown (for four values in the above example): 00001 00010 00100 01000 . Expressed in base 10, this is 1, 2, 4, 8.

#### Difference :

You can see the difference lies in the Enum.ToString() method. If your enum has the [Flags] attribute set then the ToString() will return a comma seperated values list of bitwise enum values. If there's no [Flags] attribute ToString() will return a number for every bitwise value.

#### C# Source Code

Output : 5 - with flag : Low, High

#### VB.Net Source Code

Output : 5 - with flag : Low, High

### NOTE:

Although C# always allows developers to perform bit operations on enumeration without the FlagsAttribute, Visual Basic (VB.Net) does not. So if you are exposing types to other programming languages, then marking enumeration with the FlagsAttribute is a good idea; it also makes it clear that the members of the enumeration are designed to be used together.

## Enum Basics

Enums are strongly typed constants which makes the code more readable and less prone to errors. It is useful when you have a set of values that are functionally significant and unchanged. More about.... Enum in C#

## Convert an enum to a List

The following program shows how to convert an enum to List Datastructure. More about.... Enum to List

net-informations.com (C) 2022    Founded by raps mk