Example:
public void foo(params string[] s) { ... }
We can call this method with:
a) foo(\"test\", \"test2\", \"test3\") //
Only the last parameter of a method can be a parameter array (params
) so you can't pass more than one variable into a method whose signature only takes in params
.
Therefore what you're trying to do in C
isn't possible and you have to add that string into an array, or create an overload that also takes a string parameter first.
public void foo(string firstString, params string[] s)
{
}
I think you're assuming that string[] s
accepts a single string argument as well as an array of strings, which it does not. You can achieve this via.
public static void Test(string[] array, params string[] s)
{
}
(Remember params
has to be the last argument)
And then to invoke:
Test(new string[]{"test", "test2", "test3"}, "test");
Notice how the array is passed in first, and then the argument that is passed as params
.
Just add your string to the array:
var newArray = new string[oldArray.length+1];
newArray[0]=yourString;
oldArray.CopyTo(newArray, 1);
foo(newArray);
While you can solve this without using an extension method, I actually recommend using this extension method as I find it very useful whenever I have a single object but need an IEnumerable<T> that simply returns that single object.
Extension method:
public static class EnumerableYieldExtension
{
public static IEnumerable<T> Yield<T>(this T item)
{
if (item == null)
yield break;
yield return item;
}
}
The extension method is useful in many scenarios. In your case, you can now do this:
string[] someArray = new string[] {"test1", "test2", "test3"};
foo(someArray.Concat("test4".Yield()).ToArray());