MichaelD
MichaelD

Reputation: 8767

C# 4.0, optional parameters and params do not work together

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());
}   

Upvotes: 70

Views: 25247

Answers (4)

Chris
Chris

Reputation: 1

Combining the methods above would give callers the best of both. Create an overload that uses the named parameter (C: C) so that the default value is still used for any unspecified optional parameters.

public static void TestOptional(string A, params string[] C)
{
    TestOptional(A, C: C);
}


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

Upvotes: 0

katbyte
katbyte

Reputation: 2785

This worked for me:

    static void Main(string[] args) {

        TestOptional("A");
        TestOptional("A", 1);
        TestOptional("A", 2, "C1", "C2", "C3"); 

        TestOptional("A", B:2); 
        TestOptional("A", C: new [] {"C1", "C2", "C3"}); 

        Console.ReadLine();
    }

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

Upvotes: 16

CodeMonkeyKing
CodeMonkeyKing

Reputation: 4632

Your only option right now is to overload the TestOptional (as you had to do before C# 4). Not preferred, but it cleans up the code at the point of usage.

public static void TestOptional(string A, params string[] C)
{
    TestOptional(A, 0, C);
}

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

Upvotes: 47

Mahesh Velaga
Mahesh Velaga

Reputation: 21991

Try

TestOptional("A", C: new []{ "D", "E"});

Upvotes: 17

Related Questions