Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do flags in C#

In C# I have seen enums used in a flag format before. Such as with the Regex object.

Regex regex = new Regex("expression", RegexOptions.Something | RegexOptions.SomethingElse);

If I have a custom enum:

enum DisplayType
{
    Normal,
    Inverted,
    Italics,
    Bold
}

How would i format a method to accept multiple enums for one argument such as the syntax for Regex? i.e SomeMethod(DisplayType.Normal | DisplayType.Italics);.

like image 856
Chev Avatar asked Sep 04 '25 16:09

Chev


2 Answers

Use the FlagsAttribute. The MSDN documentation explains everything. No point repeating it here.

For your example, you'd say:

[Flags]
enum DisplayType {
    None = 0,
    Normal = 1,
    Inverted = 2,
    Italics = 4,
    Bold = 8
}
like image 121
jason Avatar answered Sep 07 '25 14:09

jason


Use the FlagsAttribute, like so

[Flags]
enum DisplayType
{
    None = 0x0,
    Normal = 0x1,
    Inverted = 0x2,
    Italics = 0x4,
    Bold = 0x8
}
like image 36
Alan Avatar answered Sep 07 '25 14:09

Alan