Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 320
Ilya Kogan Avatar asked Apr 04 '11 08:04

Ilya Kogan


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

Why is C named so?

Quote from wikipedia: "A successor to the programming language B, C was originally developed at Bell Labs by Dennis Ritchie between 1972 and 1973 to construct utilities running on Unix." The creators want that everyone "see" his language. So he named it "C".


2 Answers

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.

like image 107
Mårten Wikström Avatar answered Oct 12 '22 14:10

Mårten Wikström


Pass them in as a single argument:

Bar(string.Format("Some {0} text {1} here {2}", args));
like image 30
Marcelo Cantos Avatar answered Oct 12 '22 13:10

Marcelo Cantos