December 1, 2015

Format string with String.Format() method in C#

While programming you may need to build human understandable line(s) or para with dynamic values. In such cases, mostly developers either choose string concatenation or StringBuilder option in C# language.

Manipulating strings with these results in mutability and immutability. For detail, please read difference between string concatenation and StringBuilder. Is it ok for frequent use, or in case of looping, or for large strings manipulations?

Consider second case of formatting string with some calculated dynamic values, e.g.
  1. Decimal values to currency format,
  2. Splitting of date and time from DateTime value,
  3. Multiple string manipulation etc.

These may become tricky or lengthy, if you choose general programming concepts. Also, to display user friendly messages, always in demand.

With this article, we will understand how effectively we can format dynamic value with certain constant string line(s) or in paragraph, with less number of code lines. C# provided String.Format() method to do so. Let see few examples to understand it easily:

Example: 1


decimal d = 19.789M;
String.Format("The currency value is {0:C2}", d);

Output: The currency value is $19.79

// $ will return if you have chosen culture en-US, otherwise respective currency symbol will return.
Suffix ‘2’ with ‘C’ defines number of precision pint after decimal.
---------------------------------------------------------------------------------

Example: 2

String.Format("This message generated on {0:d} at {0:t}", DateTime.Now);

Output: This message generated on 12/1/2015 at 2:24 PM
---------------------------------------------------------------------------------

Example: 3

string name1 = "John", name2 = "Bob";
String.Format("Hello {0}, you have a message from {1}", name1, name2);

Output: Hello John, you have a message from Bob
---------------------------------------------------------------------------------


For detail about format standards, please visit https://msdn.microsoft.com/en-us/library/dwhawy9k(v=vs.110).aspx