OneBite.Dev - Coding blog in a bite size

Format A String In C#

Code snippet for how to Format A String In C# with sample and detail explanation

In this article, we will discuss how to format a string in C#. We will walk you through the steps of concatenation, interpolation, and formatting with a clear example.

Code snippet for String Formatting in C#

Before delving into the explanation of the code, let’s have a look at the code snippet for a better understanding of string formatting in C#.

using System;

class StringFormatting
{
    static void Main()
    {
        string firstName = "John";
        string lastName = "Doe";
        int age = 25;
        
        // Using concatenation
        Console.WriteLine("Hello, " + firstName + " " + lastName + ". You are " + age + " years old.");

        // Using interpolation
        Console.WriteLine($"Hello, {firstName} {lastName}. You are {age} years old.");

        // Using String.Format method
        Console.WriteLine(String.Format("Hello, {0} {1}. You are {2} years old.", firstName, lastName, age));
    }
}

Code Explanation for String Formatting in C#

Let’s break down the above code snippet and understand how it’s formatting the string step by step:

  • Firstly, we include the System namespace with using System; because it contains fundamental classes and base classes that define common value and reference data types.

  • We then declare a class called StringFormatting.

  • Inside this class, we define the Main method, which is the entry point of the program.

  • We declare and initialize three variables: firstName, lastName, and age.

  • We then format the string in three different ways to print out a message including these variables:

    • By using string concatenation: Console.WriteLine("Hello, " + firstName + " " + lastName + ". You are " + age + " years old.");. Here, we combine the string literals and variables with the + operator.

    • By using string interpolation: Console.WriteLine($"Hello, {firstName} {lastName}. You are {age} years old.");. In this case, we insert the variables directly into the string literal, which is marked by the $ sign.

    • By using the String.Format method: Console.WriteLine(String.Format("Hello, {0} {1}. You are {2} years old.", firstName, lastName, age));. Here, we use the placeholders {0}, {1}, and {2} for the variables inside the string, and pass the variables as the arguments of the String.Format method.

All three methods will output the same message: “Hello, John Doe. You are 25 years old.” This makes it clear how you can format a string in C# in different ways according to your preference and needs.

c-sharp