Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum flags doesn't append value

Tags:

c#

enums

flags

I'm having a few issues in using a Flag enumeration.

My enumeration is the following (I declared the Flags attribute):

[Flags]
public enum Categ
{
    None = 0,
    Doors = 1,
    Views = 2,
    Rooms = 3,
    Spaces = 4
}

But when I try to use it in my code it seems that instead of appending the last value it replaces the first one:

var category = Categ.Doors | Categ.Rooms;
//category is always equal to Rooms only

What am I doing wrong? I'm new to Flags so maybe I'm skipping some step. Thank you very much!

like image 326
Paslet87 Avatar asked Jul 13 '26 18:07

Paslet87


1 Answers

Adding the [Flags] attribute doesn't really do anything to the enum other than affect how .ToString() works. You still need to use values that are powers of 2 for each elements:

[Flags]
public enum Categ
{
    None = 0,
    Doors = 1,
    Views = 2,
    Rooms = 4,
    Spaces = 8
    // then 16, 32, 64 etc.
}
like image 115
DavidG Avatar answered Jul 15 '26 08:07

DavidG