Skylin R
Skylin R

Reputation: 2271

C# String Format with unknown amount of parameters

Is there any way to create string with dynamic amount of parameters? For example I've got string like this:

var text = "Name: {0}, LastName: {1}, Hobbies: {2}";
Console.WriteLine(System.String.Format(text, "John", "Dohn", "Swimming")

And it's working like a charm, but what if somebody can type more hobbies for example from 1 to 10. How to create such a string with dynamic amount of hobbies?

It would be awesome to use something like that:

var text = "Name: {0}, LastName: {1}, Hobbies: {2-11}";
Console.WriteLine(System.String.Format(text, "John", "Dohn", "Swimming", "Dancing", "Singing", "Doing nothing")

Or some solution like args in functions.

And output should be like "Name: John, LastName: Dohn, Hobbies: Swimming, Dancing, Singing, Doing Nothing". But separator is not important.

Is there any way to handle that in one String Format? Or I need to do some workaround?

Upvotes: 0

Views: 196

Answers (2)

coding.monkey
coding.monkey

Reputation: 226

You can define a method that combines the suggestion from @Conyc with the params keyword to accomplish what you want (in fact, one of the string.Format overloads also uses params). Here is what that might look like:

public static string FormatHobbies(string text, string name, string lastName, params string[] hobbies) =>
    string.Format(text, name, lastName, string.Join(", ", hobbies));

Sample Input/Output:

const string text = "Name: {0}, LastName: {1}, Hobbies: {2}";
// output: Name: John, LastName: Smith, Hobbies: 
Console.WriteLine(FormatHobbies(text, "John", "Smith"));
// output: Name: Jane, LastName: Doe, Hobbies: Fishing, Hiking
Console.WriteLine(FormatHobbies(text, "Jane", "Doe", "Fishing", "Hiking"));

Upvotes: 1

Conyc
Conyc

Reputation: 460

I would recommend joining the hobbies together with string.join before formatting the final string.

var hobbies = new[] {"Swimming", "Dancing", "Singing", "Doing nothing"};
var text = "Name: {0}, LastName: {1}, Hobbies: {2}";
Console.WriteLine(System.String.Format(text, "John", "Dohn", string.Join(", ", hobbies)));

Upvotes: 2

Related Questions