Using C# 12's Interpolated Strings For More Concise And Readable Code

Interpolated strings were introduced in C# 6 as a new way to format strings with expressions. With the release of C# 12, interpolated strings have been improved to provide even more concise and readable code. This article will explore how to use C# 12's interpolated strings to make your code more expressive.

Interpolated strings allow you to embed expressions inside a string literal, using the "$" character at the beginning of the string. For example:

string name = "Amit";
int age = 30;
Console.WriteLine($"My name is {name} and I'm {age} years old.");

The output of this code will be: "My name is Amit, and I'm 30 years old." The expressions inside the curly braces will be evaluated at runtime, and their values will be included in the resulting string.

C# 12 introduces two new features for interpolated strings: format specifiers and escape sequences.

Format Specifiers

Format specifiers allow you to control how the expressions inside the interpolated string are formatted. You can use them to specify the number of decimal places, padding, and other formatting options. Format specifiers are indicated by a colon followed by a format string.

For example, consider the following code:

double pi = Math.PI;
Console.WriteLine($"The value of pi is {pi:F2}");

The output of this code will be: "The value of pi is 3.14". The "F2" format specifier tells the compiler to format the value of pi as a fixed-point number with two decimal places.

You can use format specifiers with any expression that can be formatted. For example, you can format dates, numbers, and even custom objects. The possibilities are endless.

Escape Sequences

Escape sequences allow you to include special characters inside an interpolated string. They are indicated by a backslash followed by a character. Some of the most common escape sequences are "\n" for a new line, "\t" for a tab, and "\" for a literal backslash.

For example:

string message = $"This is a message with a\nnew line and a\ttab.";
Console.WriteLine(message);

The output of this code will be:

This is a message with a
new line and a    tab.

Note that the escape sequences are interpreted when the string is constructed, not when it is displayed. This means you can use variables inside the escape sequences, which will be evaluated at runtime.

Conclusion

C# 12's interpolated strings provide a powerful and concise way to format strings with expressions. With the new format specifiers and escape sequences, you can make your code even more expressive and readable. Interpolated strings are a great addition to the C# language and should be used whenever possible.


Similar Articles