A Neat Trick with string.Format

Just a quick neat trick today that I found with string.Format.

BigBang

It’s common knowledge that you can use string.Format to replace parameters in a parameterized string. Supply the parameterized string with parameters {0}, {1}, …, {n}. Then supply <=n parameters and they will replace the parameters in the provided string up to the number you've chosen to replace.

It's important to note that this does not work if you are missing a consecutive number in the parameterized string, or if you don't start at 0.

This works:

string parameterizedString = "Hello {0}, today is {1}. The current time is {2}.";
string.Format(parameterizedString, "Chris", "Tuesday", "4:30");

// Result is "Hello Chris, today is Tuesday. The current time is 4:30."

Easy enough, right?

This doesn't work:

string parameterizedString = "Hello {0}, today is {1}. The current time is {2}.";
string resultString = string.Format(parameterizedString, "Chris", "Tuesday");

// Result is "Hello Chris, today is Tuesday. The current time is {2}."

string.Format(resultString, "4:30"); // Error!

The compiler is looking at the parameterized string and is looking for {0} to put "4:30"; into, but it doesn't find it. It doesn't care that you've got "{2}" in there.

So, here's the trick:

string parameterizedString = "Hello {0}, today is {1}. The current time is {2}.";
string resultString = string.Format(parameterizedString, "Chris", "Tuesday", "{0}");

// Result is "Hello Chris, today is Tuesday. The current time is {0}."

string.Format(resultString, "4:30");

// Result is "Hello Chris, today is Tuesday. The current time is 4:30."

Now the compiler sees that the string still contains one parameter starting at {0} and allows it to be replaced with "4:30". This allows you to complete only some parameters in your parameterized string and pass the string into different methods in order to be completed. It doesn't have to be completed in one location if it breaks the abstraction to do so. It's come in handy for me a few times, so hopefully others can find value in this as well.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s