Rob Kraft's Software Development Blog

Software Development Insights

Use string.Format instead of string concatenation

Posted by robkraft on April 15, 2011

I recently learned a good reason for writing my C# code like this:

return string.Format("{0} was deposited in your account.", amount);

instead of

return amount + " was deposited in your account.";

Both return the same result when the string is in English, but if you want your code to support other languages, then you need to be aware that the sentence structure of another language may not match English and that using string.Format gives the language translator more control over the format of the entire message. The English sentence, “The man went to the store”, may sound like, “To the store went the man” for speakers of languages that put the subject of the sentence at the end. Many bilingual speakers find these differences to be a major challenge to speaking new languages fluently. To myself, the message “$100 was deposited in your account.” sounds like good English, but in another language that may sound like “Was deposited amount of $100 to your account.”.

When you write your code using concantenation, you are forcing the translator to place part of the sentence where you would place it in your native language. But, if you use string.Format, and convert your string to a resource to support localization, the translator can fully control the translation.

return string.Format(AppResources.DepositSuccessful, amount);
en-US = AppResources.DepositSuccessful = "{0} was deposited in your account."
es-SP = AppResources.DepositSuccessful = "Fue depositado {0} en su cuenta."

Disclaimer – I am not fluent in Spanish so my translation might sound terrible to Spanish speakers. My apologies.

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

 
%d bloggers like this: