shengmin
shengmin

Reputation: 319

In C#, is there a way to pass an array to a method that takes in a variable length parameters?

Suppose I have this method I want to call, and it's from a third-party library so I cannot change its signature:

void PrintNames(params string[] names)

I'm writing this method that needs to call PrintNames:

void MyPrintNames(string[] myNames) {
  // How do I call PrintNames with all the strings in myNames as the parameter?
}

Upvotes: 0

Views: 216

Answers (2)

Mike Christensen
Mike Christensen

Reputation: 91600

Sure. The compiler will convert multiple parameters into an array, or just let you pass in an array directly.

public class Test
{
   public static void Main()
   {
      var b = new string[] {"One", "Two", "Three"};
      Console.WriteLine(Foo(b)); // Call Foo with an array

      Console.WriteLine(Foo("Four", "Five")); // Call Foo with parameters
   }

   public static int Foo(params string[] test)
   {
      return test.Length;
   }
}

Fiddle

Upvotes: 5

Konrad Morawski
Konrad Morawski

Reputation: 8394

I would try

PrintNames(myNames);

You would know if you had a look at the specs on MSDN: http://msdn.microsoft.com/en-us/library/w5zay9db.aspx

They demonstrated it quite clearly - note the comment in the sample code:

// An array argument can be passed, as long as the array 
// type matches the parameter type of the method being called. 

Upvotes: 5

Related Questions