Sometimes when reading others\' C# code I see a method that will accept multiple enum values in a single parameter. I always thought it was kind of neat, but never looked in
With the help of the posted answers and these:
I feel like I understand it pretty well.
Thanks.
I second Reed's answer. However, when creating the enum, you must specify the values for each enum member so it makes a sort of bit field. For example:
[Flags]
public enum DaysOfWeek
{
Sunday = 1,
Monday = 2,
Tuesday = 4,
Wednesday = 8,
Thursday = 16,
Friday = 32,
Saturday = 64,
None = 0,
All = Weekdays | Weekend,
Weekdays = Monday | Tuesday | Wednesday | Thursday | Friday,
Weekend = Sunday | Saturday,
// etc.
}
In my particular situation, I would like to use the System.DayOfWeek
You can not use the System.DayOfWeek as a [Flags]
enumeration because you have no control over it. If you wish to have a method that accepts multiple DayOfWeek
then you will have to use the params
keyword
void SetDays(params DayOfWeek[] daysToSet)
{
if (daysToSet == null || !daysToSet.Any())
throw new ArgumentNullException("daysToSet");
foreach (DayOfWeek day in daysToSet)
{
// if( day == DayOfWeek.Monday ) etc ....
}
}
SetDays( DayOfWeek.Monday, DayOfWeek.Sunday );
Otherwise you can create your own [Flags]
enumeration as outlined by numerous other responders and use bitwise comparisons.
Reed Copsey is correct and I would add to the original post if I could, but I cant so I'll have to reply instead.
Its dangerous to just use [Flags] on any old enum. I believe you have to explicitly change the enum values to powers of two when using flags, to avoid clashes in the values. See the guidelines for FlagsAttribute and Enum.