6

I am trying to mix optional parameters and variable length parameters (using params keyword):

Here's the function declaration:

void foo(int req, string opt = "empty", params object[] rest) {}

And here are the calls to that function:

foo(1);
foo(1, "something");
foo(1, "something", 2, 3);
foo(1, 2, 3);

The last call does not compile since parameters are provided after the omitted optional parameter. (at least I think that's why it does not work)

How can I omit the optional parameter (opt) and still be able to use the variable length parameter (rest) ?

EDIT: in fact, answer to C# 4.0, optional parameters and params do not work together does not satisfy me because of the possible many combinations of overloads in case of multiple optional parameters.

Community
  • 1
  • 1
seb
  • 71
  • 1
  • 5
  • 3
    IMO combining these two techniques just makes it more confusing than having a separate overloaded `foo()` method. – Cᴏʀʏ Feb 27 '13 at 14:48
  • @CAbbott yes indeed. I didn't search enough. – seb Feb 27 '13 at 15:04
  • You can edit this as much as you like. There isn't a way to do this cleanly. The answer that I gave to the duplicate, and this question is a duplicate that is seeking a different answer, is far from optimal syntax and I didn't claim that it was. The answer was posted as a possible work around. – CodeMonkeyKing Jun 06 '14 at 06:59

2 Answers2

3

try this

        foo(1);
        foo(1, "something");
        foo(1, "something", 2, 3);
        foo(1, rest: new object[]{2,3 });
2

This is a code smell. Something like this will be better:

public interface IFooSetup
{
    IReadOnlyList<object> Params{get;}
    string Opt{get;}
}

public class FooSetup : IFooSetup
{
    public IReadOnlyList<object> Params { get; set; }
    public string Opt { get; set; }

    public FooSetup()
    {
        Opt = "empty";
        Params = new List<object>();
    }
}

public void Foo(int req, IFooSetup setup)
{
}

You'll be able to mock isolate your test of Foo more easily, and mock your setup.

Still, you should make the optional params strongly typed, unless you absolutely cannot achieve it at compile time.

Meirion Hughes
  • 24,994
  • 12
  • 71
  • 122