Understanding the String.Format C# Function

string.Format C#The static string class in the .NET framework provides several utility functions that can be used to create, modify and manipulate string type data in applications. The string.Format method is one such utility method, which can be leveraged to flexibly apply proper and robust formatting to string type data. String.Format method has several overloads which perform varied functions with same objective — to format the string according to the application’s requirement.

How String.Format Works

String.Format is a static method which returns a formatted string. In order to specify the element markers, curly brackets are used. Inside the curly bracket, position markers are divided into two parts separated by a colon “:”. On the left side of the colon, the actual position of the object to be displayed is mentioned and on the right side of the colon, formatting options are described. Things might look confusing at the moment but the following example demonstrates how the concept of string formatting actually works.

Interested in learning more about C#? Check out this course

A basic String.Format C# Example

string name = "James";

int age = 20;

DateTime year = new DateTime(1994, 2, 14);

string sentence = string.Format("{0} was {1} years old in {2:yyyy}", name, age, year);

Console.WriteLine(sentence);

In the above example, three variables are declared: a string named name, an integer named age and a DateTime variable named year. Then, a string type variable sentence has been declared which stores a formatted string returned back by the String.Format method on the right side of the “equals to” symbol.

The parameter string in the string.Format starts with a {0} which corresponds to the first object. This is a position marker which tells the compiler that this should be replaced by the first object passed to String.Format method. The position marker {1} means that the second object would be inserted at this location in the returned string.

The third position marker is slightly different it looks like {2:yyyy}. The part to the left of the column denotes location as in case of the first two position markers while the yyyy after the colon is the format. It means that the object that the third object should be stored at this position and it should only display the year.

The actual objects are inserted in the sequence after the formatted string. Name would be displayed at the location of {0}, age would be displayed in {1}’s location and year would be displayed at {2:yyyy}’s location.

If you compile and run the above code, the following string would be displayed on the console:

James was 20 years old in 1994

It is evident from the output that the year variable contains year, month and day, but only year has been displayed. This is due to the fact that the year object has been formatted in the string.Format C# method to display year only.

For more C# tutorials, take this course

Number Formatting via String.Format in C#

Integers, floats, double and other number type data can also be formatted via string.Format method. In the following example, a value of type double has been converted into percentage using string.Format method:

string name = "James";

double marks = 0.889;

string course = "English";

string sentence = string.Format("{0} got {1:0.00%} marks in {2}", name, marks, course);

Console.WriteLine(sentence);

In the above lines of code, there are three variables. One of them is a double type, named marks. The variable contains a double value. Inside the string.Format method it has been formatted as {1:0.00%}. It means that this will be the second object in the sequence of objects passed.

The ‘%’ sign in the format multiplies the value with 100. There are two zeros on the right side of the decimal; in the output the value shown would be precise to two decimal places. The zeros on the left side of the decimal place do not matter because if multiplied by 100, the resulting value is greater than 9, it would automatically occupy two decimal places on the left. The output of the code will look like this:

James got 88.90% marks in English

Padding using String.Format C# Method

Padding can be added on the left or right side of the object to be formatted. For instance, in the following example, a padding of 15 spaces is added on the right side of the first object and a padding of 15 spaces is added on the left side of the second object:

string name = "James";

string course = "English";

string sentence = string.Format("{0, -15} passed in {1, 15}", name, course);

Console.WriteLine(sentence);

In the output, a space of 15 units will be added on the right side of the name variable. A negative padding indicates that space would be added to the right side of the object whereas positive padding adds space to the left of the job. A space of 15 units will be added to the left of the course.

Formatting strings via ToString method

You shouldn’t always use the string.Format method for formatting purposes. Particularly, if there is only one value to format, it’s more convenient to use ToString method and passing the format in its parameters. The following example formats a DateTime type variable via ToString method:

DateTime date = new DateTime(2008, 6, 4, 9, 30, 15);

string sentence = date.ToString("ddd d MMM HH:mm , yyyy");

In the above example, a DateTime type variable named date has been formatted by passing format to the ToString method as a parameter.

To specify above formatting via string.Format method, following line of code would be used:

sentence = string.Format("{0:ddd d MMM HH:mm , yyyy}", date);

It is evident from the above examples that for formatting single string values, the ToString method is preferable over the string.Format method. However, in the case of multiple values, it is more convenient to use the latter one.

To learn more about string formatting in C#, check out this course at Udemy.com