Reputation:
so imagine this, I have the following variable set to a string.format:
string foo = string.Format("{0} {1} {2} {3} {4} {5} {6} {7} {8}");
the Format method will have a lot more placeholders than this (64 to be precise) and depending on some conditions they could change. so I was wondering if there was a way to loop through a list of variables I have and then insert those variables into the format method correspondingly. I have no idea how to even start this and if it's even possible, but surely I don't have to manually insert 64 variables into the format method?
Upvotes: 0
Views: 1432
Reputation: 26971
Get a list, sort it in the order you want - then
var l = new List<string>();
// add to l, in the order you want then -
// when adding convert to the string equivalent if it's not a string already.
var s = string.Join("|",l);
return s;
Upvotes: 1
Reputation: 32068
There's an overload of String.Format
that accepts a params object[]
parameter:
public static string Format (string format, params object[] args);
This means that you can pass any number of any type of objects that you want. You are, however, responsible for ensuring that the amount of parameters passed match the number of placeholders in the string. For example:
DateTime date = DateTime.Today;
int number = 1234;
string format1 = "{0} == {1}";
string formatted = Format(format1, date, number);
// OR
object[] values = new object[] { date, number };
string formatted = Format(format1, values);
private static string Format(string text, params object[] values)
{
return string.Format(format1, values);
}
Upvotes: 1
Reputation: 12837
yes, possible. you can create a function with unspecified number of parameters using the params
keyword. something like this:
void myFunction(params object[] parameters)
{
foreach (var x in parameters) ...
}
Upvotes: -1