escargot agile
escargot agile

Reputation: 22389

C#: Converting a collection into params[]

Here is a simplification of my code:

void Foo(params object[] args)
{
    Bar(string.Format("Some {0} text {1} here {2}", /* I want to send args */);
}

string.Format requires the arguments sent as params. Is there some way I can convert the args collection into parameters for the string.Format method?

Upvotes: 10

Views: 10316

Answers (3)

Marcelo Cantos
Marcelo Cantos

Reputation: 185962

Pass them in as a single argument:

Bar(string.Format("Some {0} text {1} here {2}", args));

Upvotes: 4

Brian
Brian

Reputation: 81

You could try using object.GetType(), for example

void Foo(params object[] args)
    {
        List<string> argStrings = new List<string>();

        foreach (object arg in args)
        {
            if (args.GetType().Name == typeof(String).Name)
            {
                argStrings.Add((string)arg);
            }
            else if (args.GetType().Name == typeof(DateTime).Name)
            {
                DateTime dateArg = (DateTime)arg;
                argStrings.Add(dateArg.ToShortDateString());
            }
            else
            {
                argStrings.Add(arg.ToString());
            }
        }

        Bar(string.Format("Some {0} text {1} here {2}", argStrings.ToArray()));
    }

Upvotes: 0

M&#229;rten Wikstr&#246;m
M&#229;rten Wikstr&#246;m

Reputation: 11344

The params keyword is only syntactic sugar that allows you to call such a method with any number of arguments. However, those arguments are always passed to the method as an array.

This means that Foo(123, "hello", DateTime.Now) is equivalent to Foo(new object[] { 123, "hello", DateTime.Now }).

You can therefore pass the arguments from Foo directly to string.Format like this:

void Foo(params object[] args)
{
  Bar(string.Format("Some {0} text {1} here {2}", args));
}

However, in this particular case, you demand three arguments (because you have {0}, {1} and {2} in your format). Therefore you should change your code to:

void Foo(object arg0, object arg1, object arg2)
{
  Bar(string.Format("Some {0} text {1} here {2}", arg0, arg1, arg2));
}

...or do as Marcelo suggested.

Upvotes: 13

Related Questions