views:

95

answers:

3

An example of a method that uses the params keyword is String.Format("", foo, bar, baz)

But how would I make a method that accepts an array of enums like so:

class MyClass
{
    public enum Foo { Bar, Baz }

    public static void MyMethod(params enum[] Foo) {}

    public static void TestMethod()
    {
        MyMethod();
        MyMethod(Foo.Bar);
        MyMethod(Foo.Baz);
        MyMethod(Foo.Bar, Foo.Baz);
    }
}
+8  A: 
public static void MyMethod(params Foo[] values) { }
David Morton
Perfect, thanks!
c00lryguy
+1  A: 

Try this instead

class MyClass
{
public enum Foo { Bar, Baz }

public static void MyMethod(params Foo[] foos) {}

public static void TestMethod()
{
    MyMethod();
    MyMethod(Foo.Bar);
    MyMethod(Foo.Baz);
    MyMethod(Foo.Bar, Foo.Baz);
}

}

Thomas Wanner
+2  A: 

Err..try:

public static void MyMethod(params Foo[] foo) { }
Wim Hollebrandse
Bah. WAY too late. ;-)
Wim Hollebrandse
=p Thanks anyways. Do you know how I would merge the array of Foo enums with some defaults. for example I pass `MyMethod(Foo.Baz)` but I have `Foo.Bar` set as default so `foo` would equal `[Foo.Bar, Foo.Baz]`
c00lryguy
No that wouldn't happen automatically for you. The closest to that would be either to drop `params` and use appropriate overloaded methods, where you can obviously specify the default yourself for the first arg, and pass the 2nd on to the method that takes two arguments. Alternatively, in C# 4.0, we will have optional and named method parameters.
Wim Hollebrandse