views:

51

answers:

1

How can i create a method that has optional parameters and params together?

static void Main(string[] args)
{

    TestOptional("A",C: "D", "E");//this will not build
    TestOptional("A",C: "D"); //this does work , but i can only set 1 param
    Console.ReadLine();
}

public static void TestOptional(string A, int B = 0, params string[] C)
{
    Console.WriteLine(A);
    Console.WriteLine(B);
    Console.WriteLine(C.Count());
}   
A: 

Try

TestOptional("A", C: new []{ "D", "E"});
Mahesh Velaga
that works well for the example. but when i would need a signature like this, i am obligated to specify the type. public static void TestOptional<T>(T A, int B = 0, params Action<T>[] C)
MichaelD
@MichaelD so you dont like write similar to: Action<string> test = x => Console.WriteLine(x); Action<string> test2 = y => Console.WriteLine(y); TestOptional("A", C: new [] { test, test2 }); Am I understand correctly or what do you mean?
Nick Martyshchenko
Using your method and the signature i previously commented. The parser needs the type 'new Action<string>[]' ant not just 'new[]'. This results in much 'code-noise' when dealing with expressions of generic types and so on. Example on the simpler signature: TestOptional("A",C: new Action<string>[]{ d=>d.ToString(),d=>d.ToString()});
MichaelD