TheFormatmethodsareasetofoverloadsintheSystem.Stringclassusedtocreatestringsthatcombineobjects intospecificstringrepresentations.ThisinformationcanbeappliedtoString.Format,variousWriteLinemethods aswellasothermethodsinthe.NETframework.
Version ≥ 6.0
SinceC#6.0itispossibletousestringinterpolationinplaceofString.Format.
stringname=”John”;
stringlastname=”Doe”;
Console.WriteLine($”Hello{name}{lastname}!”);
Hello JohnDoe!
MoreexamplesforthisunderthetopicC#6.0features:Stringinterpolation.
Section12.2:PlaceswhereString.Formatis’embedded’inthe framework
ThereareseveralplaceswhereyoucanuseString.Formatindirectly:Thesecretistolookfortheoverloadwiththe signaturestringformat,paramsobject[]args,e.g.:
Console.WriteLine(String.Format(“{0}-{1}”,name,value));
Canbe replacedwith shorterversion:
Console.WriteLine(“{0}-{1}”,name,value);
ThereareothermethodswhichalsouseString.Formate.g.:
Debug.WriteLine();//andPrint()
StringBuilder.AppendFormat();
Section12.3:Createacustomformatprovider
publicclassCustomFormat:IFormatProvider,ICustomFormatter
{
publicstringFormat(stringformat,objectarg,IFormatProviderformatProvider)
{
if(!this.Equals(formatProvider))
{
returnnull;
}
if(format==”Reverse”)
{
returnString.Join(“”,arg.ToString().Reverse());
}
returnarg.ToString();
}
publicobjectGetFormat(TypeformatType)
{
returnformatType==typeof(ICustomFormatter)?this:null;
}
}
Usage:
String.Format(newCustomFormat(),”->{0:Reverse}<-“,”HelloWorld”);
Output:
->dlroWolleH<-
Section12.4:DateFormatting
DateTimedate=newDateTime(2016,07,06,18,30,14);
//Format:year,month,dayhours,minutes,seconds
Console.Write(String.Format(“{0:dd}”,date));
//FormatbyCultureinfo
String.Format(newSystem.Globalization.CultureInfo(“mn-MN”),”{0:dddd}”,date);
Version ≥ 6.0
Console.Write($”{date:ddd}”);
06
Лхагва
06
Specifier Meaning Sample Result
d Date {0:d} 7/6/2016
dd Day,zero-padded {0:dd} 06
ddd Shortdayname {0:ddd} Wed
dddd Fulldayname {0:dddd} Wednesday
D Longdate {0:D} Wednesday,July6,2016
f Fulldateandtime,short {0:f} Wednesday,July6,20166:30PM
ff Secondfractions,2digits {0:ff} 20
fff Secondfractions,3digits {0:fff} 201
ffff Secondfractions,4digits {0:ffff} 2016
F Fulldateandtime,long {0:F} Wednesday,July6,20166:30:14PM
g Defaultdateandtime {0:g} 7/6/20166:30 PM
gg Era {0:gg} A.D
hh Hour(2digits,12H) {0:hh} 06
HH Hour(2digits,24H) {0:HH} 18
M Monthandday {0:M} July6
mm Minutes,zero-padded {0:mm} 30
MM Month,zero-padded {0:MM} 07
MMM 3-lettermonthname {0:MMM} Jul
MMMM Fullmonthname {0:MMMM} July
ss Seconds {0:ss} 14
r RFC1123date {0:r} Wed,06Jul201618:30:14GMT
s Sortabledatestring {0:s} 2016-07-06T18:30:14
t Shorttime {0:t} 6:30PM
T Longtime {0:T} 6:30:14PM
tt AM/PM {0:tt} PM
u Universalsortablelocaltime {0:u} 2016-07-0618:30:14Z
U UniversalGMT {0:U} Wednesday,July6,20169:30:14AM
Y Monthandyear {0:Y} July2016
yy 2digityear {0:yy} 16
yyyy 4digityear {0:yyyy} 2016
zz 2digittimezoneoffset {0:zz} +09
zzz fulltimezoneoffset {0:zzz} +09:00
Section12.5:CurrencyFormatting
The”c” (orcurrency) formatspecifier converts anumber toa stringthat represents acurrency amount.
string.Format(“{0:c}”,112.236677)//$112.23-defaultstosystem
Precision
Defaultis2.Usec1,c2,c3andsoontocontrolprecision.
string.Format(“{0:C1}”, 112.236677) //$112.2
string.Format(“{0:C3}”, 112.236677) //$112.237
string.Format(“{0:C4}”, 112.236677) //$112.2367
string.Format(“{0:C9}”, 112.236677) //$112.236677000
CurrencySymbol
- PassCultureInfoinstancetousecustomculturesymbol.
string.Format(newCultureInfo(“en-US”),”{0:c}”,112.236677);//$112.24
string.Format(newCultureInfo(“de-
DE”),”{0:c}”,112.236677);//112,24€string.Format(newCultureInfo(“hi-
IN”),”{0:c}”,112.236677);//□112.24
2. Useanystringascurrencysymbol.UseNumberFormatInfoastocustomizecurrency symbol.
NumberFormatInfonfi=newCultureInfo(“en-US”,false).NumberFormat;
nfi=(NumberFormatInfo)nfi.Clone();
nfi.CurrencySymbol=”?”;
string.Format(nfi,”{0:C}”,112.236677);//?112.24
nfi.CurrencySymbol=”?%^&”;
string.Format(nfi,”{0:C}”,112.236677);//?%^&112.24
PositionofCurrencySymbol
UseCurrencyPositivePatternforpositivevaluesandCurrencyNegativePatternfornegativevalues.
NumberFormatInfonfi=newCultureInfo(“en-US”,false).NumberFormat; nfi.CurrencyPositivePattern=0;
string.Format(nfi,”{0:C}”,112.236677);//$112.24-default
nfi.CurrencyPositivePattern=1;
string.Format(nfi,”{0:C}”,112.236677);//112.24$
nfi.CurrencyPositivePattern=2;
string.Format(nfi,”{0:C}”,112.236677);//$112.24
nfi.CurrencyPositivePattern=3;string.Format(nfi,”{0:C
}”,112.236677);//112.24$
Negativepatternusageisthesameaspositivepattern.Alotmoreusecasespleaserefertooriginallink.
NumberFormatInfonfi=newCultureInfo(“en-US”,false).NumberFormat; nfi.CurrencyPositivePattern=0;
nfi.CurrencyDecimalSeparator=”..”;
string.Format(nfi,”{0:C}”,112.236677);//$112..24
CustomDecimalSeparator
Section12.6:Usingcustomnumberformat
NumberFormatInfocanbeusedforformattingbothintegerandfloatnumbers.
//invariantResultis“1,234,567.89”
varinvarianResult=string.Format(CultureInfo.InvariantCulture,”{0:#,###,##}”,1234567.89);
//NumberFormatInfoisoneofclassesthatimplementIFormatProvider
varcustomProvider=newNumberFormatInfo
{
NumberDecimalSeparator=”_NS_”,//willbeusedinsteadof‘,’
NumberGroupSeparator=”_GS_”,//willbeusedinsteadof‘.’
};
//customResultis“1_GS_234_GS_567_NS_89”
varcustomResult=string.Format(customProvider,”{0:#,###.##}”,1234567.89);
Section12.7:Alignleft/right,padwithspaces
Thesecondvalueinthecurlybracesdictatesthelengthofthereplacementstring.Byadjustingthesecondvalueto be positive or negative, the alignment of the string can be changed.
string.Format(“LEFT: string:->{0,-5}<-int:->{1,-5}<-“,”abc”,123);
string.Format(“RIGHT:string:->{0,5}<-int:->{1,5}<-“,”abc”,123);
Output:
LEFT: string:->abc <-int:->123 <-
RIGHT:string:-> abc<-int:-> 123<-
Section12.8:Numericformats
//Integraltypesashex
string.Format(“Hexadecimal:byte2:{0:x2};byte4:{0:X4};char:{1:x2}”,123,(int)’A’);
//Integerswiththousandseparators
string.Format(“Integer,thousandsep.:{0:#,#};fixedlength:>{0,10:#,#}<“,1234567);
//Integerwithleadingzeroes
string.Format(“Integer,leadingzeroes:{0:00};”,1);
//Decimals
string.Format(“Decimal,fixedprecision:{0:0.000};aspercents:{0:0.00%}”,0.12);
Output:
Hexadecimal:byte2:7b;byte4:007B;char:41
Integer,thousandsep.:1,234,567;fixedlength:>1,234,567<Integer,lead
ingzeroes:01;
Decimal,fixedprecision:0.120;aspercents:12.00%
TheToString()methodispresentonallreferenceobjecttypes.Thisisduetoallreferencetypesbeingderivedfrom 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
{
publicstringName{get;set; }
publicintId{get;set;}
}
…
varuser=newUser{Name=”User1″,Id=5};
Console.WriteLine(user.ToString());
However,theclassUsercanalsooverrideToString()inordertoalterthestringitreturns.Thecodefragmentbelow printsout”Id:5,Name:User1″totheconsole.
publicclassUser
{
publicstringName{get;set;}
publicintId{get;set;}
publicoverrideToString()
{
returnstring.Format(“Id:{0},Name:{1}”,Id,Name);
}
}
…
varuser=newUser{Name=”User1″,Id=5};
Console.WriteLine(user.ToString());
Section 12.10: Escaping curly brackets inside a String.Format()expression
stringoutsidetext=”Iamoutsideofbracket”;
string.Format(“{{Iaminbrackets!}}{0}”,outsidetext);
//Outputs”{Iaminbrackets!}Iamoutsideofbracket”
Section12.11:RelationshipwithToString()
WhiletheString.Format()methodiscertainlyusefulinformattingdataasstrings,itmayoftenbeabitoverkill, especiallywhendealingwithasingleobjectasseenbelow:
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 allofthesamestandardandcustomformattingstrings,butdoesn’trequirethenecessaryparametermappingas there will only be a single argument :
money.ToString(“C”); //yields”$42.00″
Caveats&FormattingRestrictions
Whilethisapproachmaybesimplerinsomescenarios,theToString()approachislimitedwithregardstoadding leftorrightpaddinglikeyoumightdowithintheString.Format()method:
String.Format(“{0,10:C}”,money); //yields” $42.00″
InordertoaccomplishthissamebehaviorwiththeToString()method,youwouldneedtouseanothermethod like PadLeft()or PadRight()respectively :
money.ToString(“C”).PadLeft(10); //yields” $42.00″
About us and this blog
We are a digital marketing company with a focus on helping our customers achieve great results across several key areas.
Request a free quote
We offer professional SEO services that help websites increase their organic search score drastically in order to compete for the highest rankings even when it comes to highly competitive keywords.
Subscribe to our newsletter!
More from our blog
See all postsRecent Posts
- Chapter120:YieldKeyword 20/05/2024
- Chapter119:LockStatement 19/05/2024
- Chapter118:Makingavariablethreadsafe 18/05/2024