Reputation: 36664
I have a method foo(params[] items)
I have a collection (List, Set, ...)
I want to send its items to foo
as items
what syntax can I use?
Upvotes: 4
Views: 70
Reputation: 3681
If you pass array as only param it will be passed as items. So just use Collection.ToArray
. Actually there is something good to know about when you're using params
. If you pass null with intention to pass it as first and only param it will be used as null array. So with code like this:
SomeMethod(null);
public void SomeMethod(params object[] items)
{
...
}
Items will be null, not array
with length of 1 and null
as first elem.
Upvotes: 4
Reputation: 45058
That method signature is invalid, so it won't compile. You still need to specify the type of the items, for instance:
foo(params string[] items) { }
then you can call it simply enough:
foo("one", "two", "three");
foo(new string { "one", "two", "three"});
foo(myCollection.ToArray());
Or,
foo(myArrayOfStrings);
Where myArrayOfStrings
is an array of strings.
You should also be sure to check for a null argument prior to iterating the items, since,
foo(null);
is valid.
Upvotes: 1