8

Example:

public void foo(params string[] s) { ... }

We can call this method with:

a) foo("test", "test2", "test3") // multiple single strings
b) foo(new string[]{"test", "test2", "test3"}) // string array

But it is not possible to call the method with:

c) foo("test", new string[]{"test", "test2", "test3"})

So when I have a single string and an array of strings, do I have to put them into one array first to call the method? Or is there a nice workaround to tell the method to consider the string array as single strings?

3
  • You have to put them into one array first Commented Aug 2, 2013 at 12:48
  • yes, you have to put them into one array...to match the function signature. Unless you add a wrapper method that takes a string and an array of strings. Commented Aug 2, 2013 at 12:49
  • use Dictionary<string,string[]> for that Commented Aug 2, 2013 at 12:49

4 Answers 4

2

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

Comments

1

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.

Comments

0

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)
{
} 

Comments

0

Just add your string to the array:

var newArray = new string[oldArray.length+1];
newArray[0]=yourString;
oldArray.CopyTo(newArray, 1);

foo(newArray);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.