C# Exception Handling
C# File I/O
C# Delegates and Events
C# Generics
C# Async Programming
C# String Formatting

C# String Formatting

C# offers several powerful ways to format strings for display, output, and logging.

1 - Composite Formatting

string msg = string.Format("Hello, {0}! You are {1} years old.", "Alice", 30);
Console.WriteLine(msg);

2 - Numeric Formats

double price = 1234.5678;

Console.WriteLine(price.ToString("C"));      // $1,234.57  (currency)
Console.WriteLine(price.ToString("F2"));     // 1234.57    (fixed 2 decimals)
Console.WriteLine(price.ToString("N0"));     // 1,235      (number, no decimals)
Console.WriteLine(price.ToString("E2"));     // 1.23E+003  (scientific)
Console.WriteLine(price.ToString("P1"));     // 123,456.8% (percent)

// Inside interpolation
Console.WriteLine($"{price:C}");  // $1,234.57
Console.WriteLine($"{price:F2}"); // 1234.57

3 - Date Formatting

DateTime dt = DateTime.Now;
Console.WriteLine(dt.ToString("yyyy-MM-dd"));          // 2024-05-01
Console.WriteLine(dt.ToString("dddd, MMMM d, yyyy")); // Wednesday, May 1, 2024
Console.WriteLine(dt.ToString("HH:mm:ss"));            // 14:30:00
Console.WriteLine($"{dt:d}");  // Short date: 5/1/2024

4 - Alignment in Interpolation

Console.WriteLine($"{"Name",-15} {"Score",5}");
Console.WriteLine($"{"Alice",-15} {95,5}");
Console.WriteLine($"{"Bob",-15} {87,5}");
// Name              Score
// Alice                95
// Bob                  87

Note: String interpolation ($"...") compiles to string.Format() under the hood, but is more readable. In performance-critical code, prefer raw StringBuilder or Span<char> to avoid allocations.

-Tip-

C# {"id":39,"topic_id":3,"name":"C# Strings","slug":"c-strings","image":null,"description":"<p>Master C# string creation, manipulation, formatting, and the modern interpolation syntax.<\/p>","icon":null,"class":null,"color":null,"status":0,"order":8,"created_at":"2026-05-03T02:03:02.000000Z","updated_at":"2026-05-03T02:03:02.000000Z"} - List of Contents

Related Tutorials: