FlagsAttribute

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

If I dont specify the [Flags] attribute on an enum to be used as a bitfield
declared as 0,1,2,4,8... and so on, and use it as one normally would with |
and & operators, would it behave differently?
 
Hi,

No.
FlagsAttribute has influence only on output, check this code (toggle the
Flags attribute to see the difference):
class Class1

{

[Flags]

public enum Flagator

{

One = 1,

Two = 2

}

[STAThread]

static void Main(string[] args)

{

Flagator ft = Flagator.One | Flagator.Two;

Console.WriteLine(ft.ToString());

Console.ReadLine();

}

}
 
Ok so it just affects the ToString() method?

I thought it affected the & and | operators.

Miha Markic said:
Hi,

No.
FlagsAttribute has influence only on output, check this code (toggle the
Flags attribute to see the difference):
class Class1

{

[Flags]

public enum Flagator

{

One = 1,

Two = 2

}

[STAThread]

static void Main(string[] args)

{

Flagator ft = Flagator.One | Flagator.Two;

Console.WriteLine(ft.ToString());

Console.ReadLine();

}

}


--
Miha Markic [MVP C#] - RightHand .NET consulting & software development
miha at rthand com
www.rthand.com

If I dont specify the [Flags] attribute on an enum to be used as a bitfield
declared as 0,1,2,4,8... and so on, and use it as one normally would
with
|
and & operators, would it behave differently?
 
As far as the math goes, no. The bitwise operators will still work
correctly. However, the Flags attribute changes the behaviour of ToString()
so that it displays the proper set(all the set flags) instead of simply one
or a simple number.

There is no guarentee that bitwise operators will work on enums without
flags in other languages.
 
Ok so it just affects the ToString() method?

I thought it affected the & and | operators.

Not in C#, but another language *may* decide to only allow the & and |
operators to work with enums declared as Flags.
 
I think thats how it should be for the operators, it makes no sense to use
bitwise operators on a non bitwise type.

I would also like to see some form of auto enumeration by base as an
attribute to it can automatically fill in 0,1,2,4,8 based on the order
unless I specify otherwise.
 
Back
Top