Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flags Enum attribute

Tags:

c#

enums

flags

What is the point of the [Flags] attribute you can bit test without it?

like image 857
Jason Wilson Avatar asked Jul 30 '10 11:07

Jason Wilson


People also ask

What does the flags attribute enable for an enum?

Flags allow an enum value to contain many values. An enum type with the [Flags] attribute can have multiple constant values assigned to it. With Flags, it is still possible to test enums in switches and if-statements. Flags can be removed or added.

What are enum flags?

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.

What is the use of Flag in C sharp?

Flag variable is used as a signal in programming to let the program know that a certain condition has met. It usually acts as a boolean variable indicating a condition to be either true or false.

What is Flag in VB?

In general, "Flag" is just another term for a true/false condition. It may have more specific meanings in more specific contexts. For instance, a CPU may keep "arithmetic flags", each one indicating a true/false condition resulting from the previous arithmetic operation.


Video Answer


1 Answers

The Flags attribute allows you to see a CSV(comma separated value) of your enumerated type when calling ToString()

For Example:

[Flags]
public Enum Permissions
{
  None =0,
  Read = 1,
  Write =2,
  Delete= 4
}

Permissions p = Permissions.Read | Permissions.Write;
p.ToString() //Prints out "Read, Write"

However you can still get the same thing if you remove the flags attribute and just do:

p.ToString("F") //Prints out "Read, Write"

And as John pointed out it also allows you convert a CSV back to Enum using Enum.Parse

like image 91
cgreeno Avatar answered Oct 08 '22 22:10

cgreeno