C# Flags vs FlagsAttribute
Asked Answered
J

1

19

What's the difference between using Flags and FlagsAttribute with an enum?

Jamarjamb answered 9/1, 2011 at 19:44 Comment(0)
I
29

Flags is simply shorthand for FlagsAttribute. In C#, you can leave the "Attribute" suffix off an attribute when you're applying it to an element.

As for Flags itself, all it does is denote the enum as having flags members. You still have to ensure that the members have values that combine correctly. Some framework functions, such as Enum.ToString, will look for the flags attribute to determine how to interpret the value.

Incriminate answered 9/1, 2011 at 19:46 Comment(1)
One way I make sure the values "combine correctly" is by starting at 0 for 'none', then each enum value increments by bitshifting one to the left .e.g: 1 << 0 (1), 1 << 1 (2), 1 << 2 (4), etc.Hausner

© 2022 - 2024 — McMap. All rights reserved.