14

So I see that it's possible to have a method signature where the first parameter provides a default value and the second parameter is a params collection.

What I can't see is a way to actually use the default value of the first argument.

Is it at all possible?

Example method:

void WaitAllTasks(string message = "Running Task.WaitAll", params Task[] tasks);

I initially tried omitting the message parameter when calling the method and also tried using named parameters, which doesn't work with params.

It compiles, but is it possible to use it?

Limbo Exile
  • 1,321
  • 2
  • 21
  • 41
Jamie Dixon
  • 53,019
  • 19
  • 125
  • 162

1 Answers1

27

I can find three ways of calling the method without specifying a value for the first parameter:

using System;

class Test
{
    static void PrintValues(string title = "Default",
                            params int[] values)
    {
        Console.WriteLine("{0}: {1}", title, 
                          string.Join(", ", values));
    }

    static void Main()
    {
        // Explicitly specify the argument name and build the array
        PrintValues(values: new int[] { 10, 20 });
        // Explicitly specify the argument name and provide a single value
        PrintValues(values: 10);
        // No arguments: default the title, empty array
        PrintValues();
    }
}

I haven't found a way of specifying multiple values without explicitly building the array though...

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • @Servy: No, reflection would require you to specify all the arguments. – Jon Skeet Oct 05 '12 at 13:24
  • 1
    It's weird that the C# compiler doesn't allow using `values: {10,20}` or `values:(10,20)`. I searched quite a lot and it seems like your way is the best way. – gdoron May 01 '13 at 14:34
  • 6
    I can see why this kind of limitation is necessary, but it's a bit unfortunate, especially with the new caller info attributes. I'd love to be able to define a method `void Info(string message, [CallerMemberName] string memberName = "", [CallerLineNumber] int lineNumber = 0, params object[] args)` on my logging wrapper. – Dan Bryant Jul 24 '14 at 13:44
  • @DanBryant: Yes, I can see that's a pain :( – Jon Skeet Jul 24 '14 at 13:46