2

Please consider this code:

public enum Status
{
    S1 = 1,
    S2 = 2,
    S3 = 3,
    S4 = 4
}

I know I can pass multiple enum using | oerator to a method:

public void DoWork(Status S)
{
}
...
DoWork(Status.S1 | Status.S2);

Now In DoWork Method I want to get values of passed enums. For Example In above code I want to get {1, 2}. How I cas do this? thanks

Arian
  • 12,793
  • 66
  • 176
  • 300
  • possible duplicate of [How do you pass multiple enum values in C#?](http://stackoverflow.com/questions/1030090/how-do-you-pass-multiple-enum-values-in-c) – rducom Feb 26 '15 at 09:41
  • 1
    You should use powers of two for the values (1, 2, 4, 8...), and mark the `Status` enum with the `[Flags]` attribute. – xanatos Feb 26 '15 at 09:42
  • @Sharped In that question I haven't seen a response that explains how to transform a (flag) Enum to an array/list of enum values – xanatos Feb 26 '15 at 09:43
  • @Sharped : No this isnot duplicate of that topic. I want to get enums values – Arian Feb 26 '15 at 09:43
  • possible duplicate of [Iterate over values in Flags Enum?](http://stackoverflow.com/questions/4171140/iterate-over-values-in-flags-enum) – xanatos Feb 26 '15 at 09:44

3 Answers3

5

Here are few steps to follow to get flagged enum :

  1. Use 2 exp (n) integer (1, 2, 4, 8, 16, 32, ...) to define your enum. Why ? : Actually each active state of your enum will take a single bit of a 32 bits integer.
  2. Add the Flags attribute.

Then,

    [Flags] 
    public enum Status
    {
        S1 = 1,
        S2 = 2,
        S3 = 4,
        S4 = 8
    }

You can use Enum.HasFlag to check if a specific status is active :

public void DoWork(Status s) 
{
    var statusResult = Enum.GetValues(typeof(Status)).Where(v => s.HasFlag(v)).ToArray() ; 

    // StatusResult should now contains {1, 2}
} 
Perfect28
  • 11,089
  • 3
  • 25
  • 45
  • 2
    There is an `HasFlag` instead of using `&` starting with .NET 4.0 – xanatos Feb 26 '15 at 09:50
  • Enum.GetValues returns an Array. The linq Where can't infer the types from usage, so a cast is required. `var statusResult = Enum.GetValues(typeof(Status)).Cast().Where(v => s.HasFlag(v)).ToArray();` – Ben May 09 '18 at 12:35
3

Declare your parameters with the params tag, then you get an array of enums:

public void DoWork (params Status[] args) {
    Console.WriteLine(args.Length);
}

Then you just pass them in as regular parameters:

DoWork(Status.S1, Status.S2);

This doesn't require changes to your enums, and easily copes with additional values. The flags solution above may work for you as well - depends on your requirements.

Lee Willis
  • 1,552
  • 9
  • 14
0

If this is the Integer values of your enums that you want you can use this :

//declare your enum as byte
public enum Status : byte
{...}
**EDITED**
//then cast it to int to use the value
DoWork((int)Status.S1 , (int)Status.S2);
//change doWork to accept int[]
public void DoWork (params int[] args)
Emmanuel M.
  • 441
  • 6
  • 11