How do you pass multiple enum values in C#?

Ronnie Overby picture Ronnie Overby · Jun 23, 2009 · Viewed 88.9k times · Source

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 into it.

Well, now I think I may have a need for it, but don't know how to

  1. set up the method signature to accept this
  2. work with the values in the method
  3. define the enum

to achieve this sort of thing.


In my particular situation, I would like to use the System.DayOfWeek, which is defined as:

[Serializable]
[ComVisible(true)]
public enum DayOfWeek
{ 
    Sunday = 0,   
    Monday = 1,   
    Tuesday = 2,   
    Wednesday = 3,   
    Thursday = 4,   
    Friday = 5,    
    Saturday = 6
}

I want to be able to pass one or more of the DayOfWeek values to my method. Will I be able to use this particular enum as it is? How do I do the 3 things listed above?

Answer

Reed Copsey picture Reed Copsey · Jun 23, 2009

When you define the enum, just attribute it with [Flags], set values to powers of two, and it will work this way.

Nothing else changes, other than passing multiple values into a function.

For example:

[Flags]
enum DaysOfWeek
{
   Sunday = 1,
   Monday = 2,
   Tuesday = 4,
   Wednesday = 8,
   Thursday = 16,
   Friday = 32,
   Saturday = 64
}

public void RunOnDays(DaysOfWeek days)
{
   bool isTuesdaySet = (days & DaysOfWeek.Tuesday) == DaysOfWeek.Tuesday;

   if (isTuesdaySet)
      //...
   // Do your work here..
}

public void CallMethodWithTuesdayAndThursday()
{
    this.RunOnDays(DaysOfWeek.Tuesday | DaysOfWeek.Thursday);
}

For more details, see MSDN's documentation on Enumeration Types.


Edit in response to additions to question.

You won't be able to use that enum as is, unless you wanted to do something like pass it as an array/collection/params array. That would let you pass multiple values. The flags syntax requires the Enum to be specified as flags (or to bastardize the language in a way that's its not designed).