#15 – Using Long Lists of Format Items in Composite Format Strings

When doing composite formatting in C# for functions that take a format string and a list of format items (e.g. String.Format), you can include any number of format items after the format string.  In other words, you could have a very long list of objects that will be substituted into the format string, like the following:

string sTest5 = string.Format("blah {0} {1} {2} {3} {4} {5} {6} {7} {8} {9} {10} ", n1, n2, n3, n4, n5, n6, n7, n8, n9, n10, n11);

You can do this because the String.Format method actually takes an array of objects as its second parameter:

public static string Format(string format, params Object[] args)

Because of the params keyword, you can pass in either an array of objects after the format string, or just a long list of parameters, which will be treated as an array of objects and used in the string substitution.

Advertisements