Getting started with C# LanguageVerbatim StringsOperatorsExtension MethodsCollection InitializersString InterpolationC# 6.0 FeaturesConstructors and FinalizersKeywordsGenericsReflectionInheritanceNull-Coalescing OperatorUsing StatementString Escape SequencesException HandlingNull-conditional OperatorsBuilt-in TypesLambda expressionsAsync-AwaitPropertiesThreadingUsing DirectiveMethodsYield KeywordEventsLINQ QueriesCommon String OperationsExpression TreesOverload ResolutionString.Formatnameof OperatorUnsafe Code in .NETInitializing PropertiesBindingList<T>ILGeneratorObject initializersXML Documentation CommentsPreprocessor directivesDynamic typeAnonymous typesStructsTuplesEnumAccess ModifiersTask Parallel LibraryAttributesGuidSingleton ImplementationDelegatesNullable typesGarbage Collector in .NetNetworkingArraysEquality OperatorLock StatementAction FiltersXmlDocument and the System.Xml namespaceDateTime MethodsBackgroundWorkerPolymorphismStatic ClassesIndexerIDisposable interfaceAliases of built-in typesImmutabilityXDocument and the System.Xml.Linq namespaceC# 7.0 FeaturesPerforming HTTP requestsGenerating Random Numbers in C#LoopingNamed ArgumentsDiagnosticsInterfacesIEnumerableNaming ConventionsAn overview of c# collectionsChecked and UncheckedRecursionFunctional ProgrammingLiteralsCastingNullReferenceExceptionFunc delegatesLINQ to XMLHash FunctionsHandling FormatException when converting string to other typesCryptography (System.Security.Cryptography)INotifyPropertyChanged interfaceValue type vs Reference typeC# 4.0 FeaturesIQueryable interfaceTask Parallel Library (TPL) Dataflow ConstructsStreamRuntime CompileConditional StatementsInteroperabilityOverflowEquals and GetHashCodeType ConversionParallel LINQ (PLINQ)String ManipulationString ConcatenatePartial class and methodsStopwatchesRegex ParsingC# ScriptC# 3.0 FeaturesAsync/await, Backgroundworker, Task and Thread ExamplesTimersFunction with multiple return valuesBinary SerializationMaking a variable thread safeIComparableCode ContractsIteratorsAssemblyInfo.cs ExamplesFile and Stream I/OCode Contracts and AssertionsCachingC# 5.0 FeaturesImplementing Flyweight Design PatternStringBuilderImplementing Decorator Design PatternAccessing DatabasesT4 Code GenerationMicrosoft.Exchange.WebServices.NET Compiler Platform (Roslyn)Data AnnotationUsing SQLite in C#System.Management.AutomationFileSystemWatcherSystem.DirectoryServices.Protocols.LdapConnectionNamed and Optional ArgumentsComments and regionsC# Authentication handlerPointers & Unsafe CodePointersHow to use C# Structs to create a Union type (Similar to C Unions)BigIntegerDependency InjectionReactive Extensions (Rx)Creational Design PatternsCreating a Console Application using a Plain-Text Editor and the C# Compiler (csc.exe)Reading and writing .zip filesGeneric Lambda Query BuilderImport Google ContactsLambda ExpressionsCLSCompliantAttributeObservableCollection<T>Synchronization Context in Async-AwaitICloneableRead & Understand StacktracesLinq to ObjectsASP.NET IdentityAccess network shared folder with username and passwordAsynchronous SocketStructural Design PatternsO(n) Algorithm for circular rotation of an arrayCreating Own MessageBox in Windows Form ApplicationIncluding Font ResourcesObject Oriented Programming In C#Using json.netGetting Started: Json with C#Windows Communication Foundation

String.Format

Other topics

Remarks:

Notes:

  • String.Format() handles null arguments without throwing an exception.
  • There are overloads that replace the args parameter with one, two, or three object parameters.

Places where String.Format is 'embedded' in the framework

There are several places where you can use String.Format indirectly: The secret is to look for the overload with the signature string format, params object[] args, e.g.:

Console.WriteLine(String.Format("{0} - {1}", name, value));

Can be replaced with shorter version:

Console.WriteLine("{0} - {1}", name, value);

There are other methods which also use String.Formate.g.:

Debug.WriteLine(); // and Print()
StringBuilder.AppendFormat();

Using custom number format

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 IFormatProvider
var customProvider = new NumberFormatInfo
{
    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);

Create a custom format provider

public class CustomFormat : IFormatProvider, ICustomFormatter
{
    public string Format(string format, object arg, IFormatProvider formatProvider)
    {
        if (!this.Equals(formatProvider))
        {
            return null;
        }

        if (format == "Reverse")
        {
            return String.Join("", arg.ToString().Reverse());
        }

        return arg.ToString();
    }

    public object GetFormat(Type formatType)
    {
        return formatType==typeof(ICustomFormatter) ? this:null;
    }
}

Usage:

String.Format(new CustomFormat(), "-> {0:Reverse} <-", "Hello World");

Output:

-> dlroW olleH <-

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.

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<-

Numeric formats

// Integral types as hex
string.Format("Hexadecimal: byte2: {0:x2}; byte4: {0:X4}; char: {1:x2}", 123, (int)'A');

// Integers with thousand separators
string.Format("Integer, thousand sep.: {0:#,#}; fixed length: >{0,10:#,#}<", 1234567);

// Integer with leading zeroes
string.Format("Integer, leading zeroes: {0:00}; ", 1);

// Decimals
string.Format("Decimal, fixed precision: {0:0.000}; as percents: {0:0.00%}", 0.12);

Output:

Hexadecimal: byte2: 7b; byte4: 007B; char: 41
Integer, thousand sep.: 1,234,567; fixed length: > 1,234,567<
Integer, leading zeroes: 01; 
Decimal, fixed precision: 0.120; as percents: 12.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.

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

Currency Symbol

  1. Pass CultureInfo instance to use custom culture symbol.
string.Format(new CultureInfo("en-US"), "{0:c}", 112.236677); //$112.24
string.Format(new CultureInfo("de-DE"), "{0:c}", 112.236677); //112,24 €
string.Format(new CultureInfo("hi-IN"), "{0:c}", 112.236677); //₹ 112.24
  1. Use any string as currency symbol. Use NumberFormatInfo as to customize currency symbol.
NumberFormatInfo nfi = new CultureInfo( "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

Position of Currency Symbol

Use CurrencyPositivePattern for positive values and CurrencyNegativePattern for negative values.

NumberFormatInfo nfi = new CultureInfo( "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 $

Negative pattern usage is the same as positive pattern. A lot more use cases please refer to original link.

Custom Decimal Separator

NumberFormatInfo nfi = new CultureInfo( "en-US", false ).NumberFormat;        
nfi.CurrencyPositivePattern = 0;
nfi.CurrencyDecimalSeparator = "..";
string.Format(nfi, "{0:C}", 112.236677); //$112..24

Since C# 6.0

6.0

Since C# 6.0 it is possible to use string interpolation in place of String.Format.

string name = "John";
string lastname = "Doe";
Console.WriteLine($"Hello {name} {lastname}!");

Hello John Doe!

More examples for this under the topic C# 6.0 features: String interpolation.

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"

Date Formatting

DateTime date = new DateTime(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(new System.Globalization.CultureInfo("mn-MN"),"{0:dddd}",date);
6.0
Console.Write($"{date:ddd}");

output :

06
Лхагва
06
SpecifierMeaningSampleResult
dDate{0:d}7/6/2016
ddDay, zero-padded{0:dd}06
dddShort day name{0:ddd}Wed
ddddFull day name{0:dddd}Wednesday
DLong date{0:D}Wednesday, July 6, 2016
fFull date and time, short{0:f}Wednesday, July 6, 2016 6:30 PM
ffSecond fractions, 2 digits{0:ff}20
fffSecond fractions, 3 digits{0:fff}201
ffffSecond fractions, 4 digits{0:ffff}2016
FFull date and time, long{0:F}Wednesday, July 6, 2016 6:30:14 PM
gDefault date and time{0:g}7/6/2016 6:30 PM
ggEra{0:gg}A.D
hhHour (2 digits, 12H){0:hh}06
HHHour (2 digits, 24H){0:HH}18
MMonth and day{0:M}July 6
mmMinutes, zero-padded{0:mm}30
MMMonth, zero-padded{0:MM}07
MMM3-letter month name{0:MMM}Jul
MMMMFull month name{0:MMMM}July
ssSeconds{0:ss}14
rRFC1123 date{0:r}Wed, 06 Jul 2016 18:30:14 GMT
sSortable date string{0:s}2016-07-06T18:30:14
tShort time{0:t}6:30 PM
TLong time{0:T}6:30:14 PM
ttAM/PM{0:tt}PM
uUniversal sortable local time{0:u}2016-07-06 18:30:14Z
UUniversal GMT{0:U}Wednesday, July 6, 2016 9:30:14 AM
YMonth and year{0:Y}July 2016
yy2 digit year{0:yy}16
yyyy4 digit year{0:yyyy}2016
zz2 digit timezone offset{0:zz}+09
zzzfull time zone offset{0:zzz}+09:00

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.

public class User
{
    public string Name { get; set; }
    public int Id { get; set; }
}

...

var user = new User {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.

public class User
{
    public string Name { get; set; }
    public int Id { get; set; }
    public override ToString()
    {
        return string.Format("Id: {0}, Name: {1}", Id, Name);
    }
}

...

var user = new User {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, 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 :

String.Format("{0,10:C}", money);  // yields "    $42.00"

In order to accomplish this same behavior with the ToString() method, you would need to use another method like PadLeft() or PadRight() respectively :

money.ToString("C").PadLeft(10);  // yields "    $42.00"

Syntax:

  • string.Format(string format, params object[] args)
  • string.Format(IFormatProvider provider, string format, params object[] args)
  • $"string {text} blablabla" // Since C#6

Parameters:

ParameterDetails
formatA composite format string, which defines the way args should be combined into a string.
argsA sequence of objects to be combined into a string. Since this uses a params argument, you can either use a comma-separated list of arguments or an actual object array.
providerA collection of ways of formatting objects to strings. Typical values include CultureInfo.InvariantCulture and CultureInfo.CurrentCulture.

Contributors

Topic Id: 79

Example Ids: 360,362,2673,4950,4951,4972,6206,7868,11323,16524,19333

This site is not affiliated with any of the contributors.