C# String Format() Method

You are Here:

C# String Format()

The Format() method formats strings in a desired format by inserting objects and variables with specified padding into other strings.

Note: This method manages formatting including the position, alignment, and format type.

Example

C# Compiler
using System; namespace myApp { class Program { static void Main(string[] args) { string s = "Name: {0} {1}"; string msg = string.Format(s, "John", "Doe"); Console.WriteLine("Format Result: {0}", msg); } } }

Output

Format Result: Name: John Doe

Syntax

public string Format(s, obj1, obj2, ...)

Parameter Values

ValueTypeExplanation
sRequiredSpecifies a string.
obj1, obj2, ...RequiredSpecifies objects to replace one or more format items in a string.

Return Value

ValueExplanation
StringReturns a formatted string.

More Examples

We can specify that value (like a float) can be formatted inside string.Format.

The format string in this example uses the 0:0.00% syntax. This means that the second argument is formatted with the pattern 0.00%.

Note: The "0.00%" part specifies the number of digits. We can have many digits before the decimal place, but only two digits after it.

Example

C# Compiler
using System; namespace myApp { class Program { static void Main(string[] args) { float mark = 0.98587f; string s = "I scored {0:0.00%} in programming"; string msg = string.Format(s, mark); Console.WriteLine("Format Result: {0}", msg); } } }

Output

Format Result: I scored 98.59% in programming

Formatting a string with specified padding.

Note: A negative number will add padding to the right (left-align). whereas, a positive padding size to add padding to the left (right-align).

Example

C# Compiler
using System; namespace myApp { class Program { static void Main(string[] args) { string s = "Name: {0, 5} {1, 10}"; string msg = string.Format(s, "John", "Doe"); Console.WriteLine("Format Result: {0}", msg); } } }

Output

Format Result: Name: John Doe

Formatting a single number, like an integer or long.

Example

C# Compiler
using System; namespace myApp { class Program { static void Main(string[] args) { int value = 123; string msg = string.Format("{0:0000}", value); Console.WriteLine("Format Result: {0}", msg); } } }

Output

Format Result: 0123

Reminder

Hi Developers, we almost covered 90% of String functions and Interview Question on C# with examples for quick and easy learning.

We are working to cover every Single Concept in C#.

Please do google search for:

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author