0

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? } 
1
  • Your question is very ambiguous. You can call it with a string array of any length, or you can use the params keyword to allow calling the method with any number of arguments (provided they're the same type) Commented Oct 9, 2013 at 22:45

2 Answers 2

5

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. 
Sign up to request clarification or add additional context in comments.

2 Comments

I see, initially I had IList<string> myNames
@shengmin IList<T> implements IEnumerable<T>, which means that you could have used myNames.ToArray(), as in PrintNames(myNames.ToArray()); :) Thanks for accepting my answer!
5

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.