Flags
attribute indicates that an enumeration can be treated as bit fields (Set of
flags).
[Flags]
enum DaysWithFlags
{
SUNDAY = 1,
MONDAY = 2,
TUESDAY = 4,
WEDNESDAY = 8,
THRUSDAY = 16,
FRIDAY = 32,
SATURDAY = 64
}
Note
that [Flags] by itself doesn't change this at all - all it does is enable a
nice representation by the .ToString() method
String
result1 = (DaysWithFlags.MONDAY | DaysWithFlags.TUESDAY |
DaysWithFlags.WEDNESDAY | DaysWithFlags.THRUSDAY |
DaysWithFlags.FRIDAY).ToString();
‘result1’
has the value "MONDAY, TUESDAY, WEDNESDAY, THRUSDAY, FRIDAY".
If
you don’t specify the [Flags] attribute on enum type, the | operator performs
bit wise or and toString method return the result of bitwise or’s of the enum
constants.
Following
is the working application.
using System; class Program { [Flags] enum DaysWithFlags { SUNDAY = 1, MONDAY = 2, TUESDAY = 4, WEDNESDAY = 8, THRUSDAY = 16, FRIDAY = 32, SATURDAY = 64 } enum DaysWithOutFlags { SUNDAY = 1, MONDAY = 2, TUESDAY = 4, WEDNESDAY = 8, THRUSDAY = 16, FRIDAY = 32, SATURDAY = 64 } static void Main() { String resultWithFlags = (DaysWithFlags.MONDAY | DaysWithFlags.TUESDAY | DaysWithFlags.WEDNESDAY | DaysWithFlags.THRUSDAY | DaysWithFlags.FRIDAY).ToString(); String resultWithoutFlags = (DaysWithOutFlags.MONDAY | DaysWithOutFlags.TUESDAY | DaysWithOutFlags.WEDNESDAY | DaysWithOutFlags.THRUSDAY | DaysWithOutFlags.FRIDAY).ToString(); Console.WriteLine("resultWithFlags {0}", resultWithFlags); Console.WriteLine("resultWithoutFlags {0}", resultWithoutFlags); } }
Output
resultWithFlags MONDAY, TUESDAY, WEDNESDAY, THRUSDAY, FRIDAY resultWithoutFlags 62
No comments:
Post a Comment