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.
These may become tricky or lengthy, if you choose general programming concepts. Also, to display user friendly messages, always in demand.
Example: 1
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.
- Decimal values to currency format,
- Splitting of date and time from DateTime value,
- 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
No comments:
Post a Comment