Enums are a great tool. They give meaning to meaningless numbers.
I love using them as flags since it couldn't be simpler. So i always used the [Flags] attribute on my enums
But why do we need that attribute? You can bitwise non [Flags]'d enums just the same.
The difference lies in the Enum.ToString() method. If your enum has the [Flags] attribute set then the ToString() will return a
CSV separated list of bitwised enum values. If there's no [Flags] attribute ToString() will return a number for every bitwised value.
As always it's best ilustrated with an example:
[Flags]
enum StateWithFlags
{
None = 0,
Read = 1,
Write = 2,
Delete = 4
}
enum StateWithNoFlags
{
None = 0,
Read = 1,
Write = 2,
Delete = 4
}
for (int enumValue = 0; enumValue <= 4; enumValue++)
Console.WriteLine("StateWithFlags: " + enumValue.ToString() + " " + ((StateWithFlags)enumValue).ToString());
/*
this returns:
0 None
1 Read
2 Write
3 Read, Write
4 Delete
*/
for (int enumValue = 0; enumValue <= 4; enumValue++)
Console.WriteLine("StateWithNoFlags: " + enumValue.ToString() + " " + ((StateWithNoFlags)enumValue).ToString());
/*
this returns:
0 None
1 Read
2 Write
3 3
4 Delete
*/
So we see that the flags attribute is quite handy when trying to simply display the combination of our choices.