Composite formatting helps you create strings by mixing fixed text with variable values easily.
0
0
Composite formatting in C Sharp (C#)
Introduction
When you want to show a message with numbers or names inside it.
When you need to build a sentence that changes based on data.
When you want to format dates, numbers, or other values in a readable way.
When you want to print multiple values in one line clearly.
When you want to control how many decimal places a number shows.
Syntax
C Sharp (C#)
string.Format("text {index:format} text", value0, value1, ...);Use curly braces { } to mark where values go inside the string.
Inside the braces, index is the position of the value, and format is optional to control how the value looks.
Examples
Insert a simple string value at position 0.
C Sharp (C#)
string result = string.Format("Hello, {0}!", "Alice"); // result is "Hello, Alice!"
Insert a number value at position 0.
C Sharp (C#)
string result = string.Format("You have {0} new messages.", 5); // result is "You have 5 new messages."
Format a number as currency with 2 decimals.
C Sharp (C#)
string result = string.Format("Price: {0:C2}", 12.5); // result is "Price: $12.50" (currency format)
Format a date in year-month-day format.
C Sharp (C#)
string result = string.Format("Date: {0:yyyy-MM-dd}", DateTime.Now); // result is "Date: 2024-06-01" (example date)
Sample Program
This program creates a message with a name, age, and height formatted to 2 decimal places.
C Sharp (C#)
using System; class Program { static void Main() { string name = "Bob"; int age = 30; double height = 1.75; string message = string.Format("Name: {0}, Age: {1}, Height: {2:F2} meters", name, age, height); Console.WriteLine(message); } }
OutputSuccess
Important Notes
Index numbers start at 0 and match the order of values after the string.
You can use format specifiers like F2 for fixed decimals, C for currency, or date formats.
Composite formatting helps keep your code clean and easy to read.
Summary
Composite formatting mixes text and values in one string easily.
Use curly braces with index numbers to place values.
Format specifiers control how values appear, like decimals or dates.