C# Strings  

C# String Formatting Explained With Practical Examples

πŸš€ Introduction

String formatting is one of the most fundamental concepts in C# development, yet it is often overlooked until developers face real world requirements such as building readable user interfaces, generating reports, formatting logs, or presenting localized content. Whether you are working with numeric values, dates, currency, or dynamic messages, string formatting gives you precise control over how data is displayed. C# offers multiple approaches to string formatting, including the classic String.Format method and the modern string interpolation syntax, and understanding both is important because production applications frequently contain a combination of legacy and newer code.

🧠 What Is String Formatting in C#

String formatting in C# is the process of inserting values into a string while controlling how those values appear when rendered. This includes defining decimal precision, applying currency symbols, formatting dates according to specific patterns or cultures, and aligning text for structured output. Instead of relying on default conversions, formatting allows developers to explicitly define presentation rules, which results in clearer output and a more professional user experience.

🧩 Using String.Format in C#

The String.Format method has been part of .NET since its early releases and is still widely used across existing applications and libraries. It works by defining indexed placeholders inside a string and replacing them with corresponding values provided as arguments at runtime.

string message = String.Format("Hello {0}, you have {1} new messages", "Mahesh", 5);
Console.WriteLine(message);

This approach is especially common in older codebases and localization scenarios where placeholders are dynamically mapped at runtime.

πŸ”’ Formatting Numbers in C#

Numeric formatting is one of the most common use cases for string formatting, particularly when displaying prices, measurements, or calculated values.

double price = 123.4567;
string result = String.Format("Price: {0:F2}", price);
Console.WriteLine(result);

This example formats the number to two decimal places, ensuring consistent output regardless of the original value. Currency formatting can also be applied using standard format specifiers.

decimal amount = 2500;
string result = String.Format("Total: {0:C}", amount);
Console.WriteLine(result);

The output adapts automatically based on the system’s culture settings, making it suitable for international applications.

πŸ“… Formatting Dates and Time

Dates and times frequently need to be presented in a human readable format, especially in dashboards, reports, and notifications.

DateTime today = DateTime.Now;
string result = String.Format("Today is {0:MMMM dd, yyyy}", today);
Console.WriteLine(result);

This approach allows full control over how date components such as month, day, and year are displayed, which is essential when working with global users or formal documentation.

πŸ“ Text Alignment and Padding

String formatting is also useful for aligning output, particularly in console applications and structured text reports where readability depends on consistent spacing.

string result = String.Format("{0,-10} {1,10}", "Item", "Price");
Console.WriteLine(result);

Alignment specifiers ensure that values line up correctly, making tabular output easier to read.

✨ String Interpolation in Modern C#

String interpolation is the preferred approach in modern C# because it improves readability and reduces the cognitive overhead of tracking placeholder indexes. By prefixing a string with the dollar sign, variables and expressions can be embedded directly into the string.

string name = "Mahesh";
int messages = 5;
string result = $"Hello {name}, you have {messages} new messages";

This syntax is easier to read and maintain, especially when working with complex strings.

πŸ” Formatting with String Interpolation

String interpolation supports the same formatting capabilities as String.Format, including numeric and date formatting.

double price = 123.4567;
string result = $"Price: {price:F2}";

Date formatting works the same way.

DateTime today = DateTime.Now;
string result = $"Today is {today:MMMM dd, yyyy}";

This makes interpolation a complete replacement for most String.Format use cases in modern applications.

βš–οΈ String.Format vs String Interpolation

Both approaches are valid and widely supported, but they serve different purposes depending on the context. String.Format is useful when working with legacy systems, localization frameworks, or scenarios where format strings are dynamically generated. String interpolation is better suited for new development because it improves readability, reduces errors, and aligns with modern C# coding standards. In most cases, string interpolation should be the default choice unless there is a specific reason to use String.Format.

❌ Common Mistakes Developers Make

Developers often misuse placeholder indexes, ignore culture specific formatting, overuse String.Format in new code, or hardcode date and number formats without considering international users. These mistakes can lead to confusing output, localization issues, and harder to maintain code, especially as applications grow in complexity.

Insert a single object in a C# string

We can insert one or more objects and expressions in a string at a specified position using the String.Format method. The position in the string starts at 0th index.

For a single object formatting, the first argument is the format and the second argument is the value of the object. The object is replaced at the {0} position in the string. 

public static string Format (string format, object arg0);  
The following code example in Listing 1 inserts a DateTime object in an existing string format.  
/* *** Simple String.Format **/  
string date = String.Format("Today's date is {0}", DateTime.Now);  
Console.WriteLine(date);  

Listing 1.

As you can see from the above code example, {0} is at the last potion in the string and the second argument is a DateTime.Now. In this case, string portion {0} will be replaced by the value of DateTime.Now in the string. Figure 1 is the result of above code in Listing 1.

Format String in C#

Figure 1.

Insert multiple objects in a C# string

We can insert multiple objects or expressions in a string to give it a desired format. The following code example in Listing 2 creates a string by inserting 5 objects. 

/* *** String.Format with multiple objects **/  
string author = "Mahesh Chand";  
string book = "Graphics Programming with GDI+";  
int year = 2003;  
decimal price = 49.95m;  
string publisher = "APress";  
  
// Book details  
string bookDetails = String.Format("{0} is the author of book {1} \n " +  
"published by {2} in year {3}. \n Book price is ${4}. ",  
author, book, publisher, year, price);  
Console.WriteLine(bookDetails); 

Listing 2.

As you can see from the above code example, the String.Format has placeholders for objects, starting at the 0th to 4th index. The {0} is replaced by the first object passed in the method, {1} is replaced by the second object passed in the method and so on.

The output of Listing 2 looks like Figure 2.

String Format C#

Figure 2.

Alignment and spacing using C# String Format

Besides the index, alignment and formatString are two optional arguments of String.Format method. Alignment is followed by index and separated by a comma as you can see in the following syntax. 

String.Format("{index[,alignment][:formatString]}", object);

By default, strings are right-aligned within their field if you specify a field width. To left-align strings in a field, you preface the field width with a negative sign, such as {0,-12} to define a 12-character right-aligned field.

The following code example in Listing 3 creates a formatted table of items with spacing between items that displays a list of published books with their title, price, publisher, and year published. 

Console.WriteLine("***** Alignment ****/");  
string[] books = {"A Programmer's Guide to ADO.NET", "Graphics Programming", "Programming C#"};  
string[] publishers = {"APress", "Addision Wesley", "C# Corner" };  
decimal[] prices = { 45.95m, 54.95m, 49.95m };  
int[] years = { 2001, 2002, 2003 };  
  
Console.WriteLine("Mahesh Chand's Books");  
String data = String.Format("{0,-35} {1,-20} {2,-10} {3, -10} \n",  
"Title", "Publisher", "Price", "Year");  
for (int index = 0; index < years.Length; index++)  
data += String.Format("{0,-35} {1,-20} {2, -10} {3, -10} \n",  
books[index], publishers[index], prices[index], years[index]);  
Console.WriteLine($"\n{data}");  

Listing 3.

The output of Listing 3 looks like Figure 3.

String.Format() Method

Figure 3.

Format using C# String Format

The formatString optional arguments of String.Format method defines how an object is formatted. All standard and custom formats may be applied to the string. Check out Formatting Types in .NET to learn more about formats and their syntaxes.

As defined in the following syntax, the format specifier is followed by a colon β€˜:’. 

String.Format("{index[,alignment][:formatString]}", object);

The following code example in Listing 4 uses format specifiers for number, decimal, and date respectively.  

// Number formatting  
int num = 302;  
string numStr = String.Format("Number {0, 0:D5}", num);  
Console.WriteLine(numStr);  
  
// Decimal formatting  
decimal money = 99.95m;  
string moneyStr = String.Format("Money {0, 0:C2}", money);  
Console.WriteLine(moneyStr);  
  
// DateTime formatting  
DateTime now = DateTime.Now;  
string dtStr = String.Format("{0:d} at {0:t}", now);  
Console.WriteLine(dtStr);

Listing 4.

The output of Listing 3 looks like Figure 4.

String.Format()

Figure 4

❓ Frequently Asked Questions

What is String.Format in C#

String.Format is a method that inserts values into a string using indexed placeholders and optional format specifiers to control how data is displayed.

Is string interpolation better than String.Format

String interpolation is generally preferred for new development because it is more readable and easier to maintain, although performance differences are usually negligible in real world applications.

Can I format dates and numbers using string interpolation

Yes, string interpolation supports the same format specifiers as String.Format for numbers, dates, currency, and custom formats.

Which approach should I use today

Use string interpolation for modern C# applications and rely on String.Format when maintaining legacy code or working with localization systems that require indexed placeholders.

Summary

In this code example, we learned how to format strings in C# using String.Format method.