Places where String.Format is 'embedded' in the framework
There are several places where you can use String.Formatindirectly: The secret is to look for the overload with the signature string format, params object[] args, e.g.:
DateTime date =newDateTime(2016,07,06,18,30,14);// Format: year, month, day hours, minutes, seconds
Console.Write(String.Format("{0:dd}",date));//Format by Culture info
String.Format(newSystem.Globalization.CultureInfo("mn-MN"),"{0:dddd}",date);
Console.Write($"{date:ddd}");
output :
06
Лхагва
06
Specifier
Meaning
Sample
Result
d
Date
{0:d}
7/6/2016
dd
Day, zero-padded
{0:dd}
06
ddd
Short day name
{0:ddd}
Wed
dddd
Full day name
{0:dddd}
Wednesday
D
Long date
{0:D}
Wednesday, July 6, 2016
f
Full date and time, short
{0:f}
Wednesday, July 6, 2016 6:30 PM
ff
Second fractions, 2 digits
{0:ff}
20
fff
Second fractions, 3 digits
{0:fff}
201
ffff
Second fractions, 4 digits
{0:ffff}
2016
F
Full date and time, long
{0:F}
Wednesday, July 6, 2016 6:30:14 PM
g
Default date and time
{0:g}
7/6/2016 6:30 PM
gg
Era
{0:gg}
A.D
hh
Hour (2 digits, 12H)
{0:hh}
06
HH
Hour (2 digits, 24H)
{0:HH}
18
M
Month and day
{0:M}
July 6
mm
Minutes, zero-padded
{0:mm}
30
MM
Month, zero-padded
{0:MM}
07
MMM
3-letter month name
{0:MMM}
Jul
MMMM
Full month name
{0:MMMM}
July
ss
Seconds
{0:ss}
14
r
RFC1123 date
{0:r}
Wed, 06 Jul 2016 18:30:14 GMT
s
Sortable date string
{0:s}
2016-07-06T18:30:14
t
Short time
{0:t}
6:30 PM
T
Long time
{0:T}
6:30:14 PM
tt
AM/PM
{0:tt}
PM
u
Universal sortable local time
{0:u}
2016-07-06 18:30:14Z
U
Universal GMT
{0:U}
Wednesday, July 6, 2016 9:30:14 AM
Y
Month and year
{0:Y}
July 2016
yy
2 digit year
{0:yy}
16
yyyy
4 digit year
{0:yyyy}
2016
zz
2 digit timezone offset
{0:zz}
+09
zzz
full time zone offset
{0:zzz}
+09:00
Currency Formatting
The "c" (or currency) format specifier converts a number to a string that represents a currency amount.
string.Format("{0:c}",112.236677)// $112.23 - defaults to system
Precision
Default is 2. Use c1, c2, c3 and so on to control precision.
NumberFormatInfo can be used for formatting both integer and float numbers.
// invariantResult is "1,234,567.89"var invarianResult =string.Format(CultureInfo.InvariantCulture,"{0:#,###,##}",1234567.89);// NumberFormatInfo is one of classes that implement IFormatProvidervar customProvider =newNumberFormatInfo{
NumberDecimalSeparator ="_NS_",// will be used instead of ','
NumberGroupSeparator ="_GS_",// will be used instead of '.'};// customResult is "1_GS_234_GS_567_NS_89"var customResult =string.Format(customProvider,"{0:#,###.##}",1234567.89);
Align left/ right, pad with spaces
The second value in the curly braces dictates the length of the replacement string.
By adjusting the second value to be positive or negative, the alignment of the string can be changed.
Escaping curly brackets inside a String.Format() expression
string outsidetext ="I am outside of bracket";string.Format("{{I am in brackets!}} {0}", outsidetext);//Outputs "{I am in brackets!} I am outside of bracket"
ToString()
The ToString() method is present on all reference object types. This is due to all reference types being derived from Object which has the ToString() method on it. The ToString() method on the object base class returns the type name. The fragment below will print out "User" to the console.
publicclassUser{publicstring Name {get;set;}publicint Id {get;set;}}...var user =newUser{Name ="User1", Id =5};
Console.WriteLine(user.ToString());
However, the class User can also override ToString() in order to alter the string it returns. The code fragment below prints out "Id: 5, Name: User1" to the console.
publicclassUser{publicstring Name {get;set;}publicint Id {get;set;}publicoverrideToString(){returnstring.Format("Id: {0}, Name: {1}", Id, Name);}}...var user =newUser{Name ="User1", Id =5};
Console.WriteLine(user.ToString());
Relationship with ToString()
While the String.Format() method is certainly useful in formatting data as strings, it may often be a bit overkill, especially when dealing with a single object as seen below :
String.Format("{0:C}", money);// yields "$42.00"
An easier approach might be to simply use the ToString() method available on all objects within C#. It supports all of the same standard and custom formatting strings(opens new window), but doesn't require the necessary parameter mapping as there will only be a single argument :
money.ToString("C");// yields "$42.00"
Caveats & Formatting Restrictions
While this approach may be simpler in some scenarios, the ToString() approach is limited with regards to adding left or right padding like you might do within the String.Format() method :
A sequence of objects to be combined into a string. Since this uses a params(opens new window) argument, you can either use a comma-separated list of arguments or an actual object array.