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?
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 ...
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.
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".
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.
Pass them in as a single argument:
Bar(string.Format("Some {0} text {1} here {2}", args));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With