Monday, January 30, 2023

C# 11.0: Newlines in String Interpolation Expressions

In this post let's have a look at another feature that is available with C# 11.0. And that is support for Newlines in String Interpolation Expressions.

Consider the following example code written in C# 10.0.
int age = 60;
string ageCategory = age switch
{
< 1 => "Infant",
< 12 => "Child",
< 17 => "Adolescent",
< 65 => "Adult",
_ => "Older adult"
};
string message = $"Based on the Age of {age}, you are a(n) {ageCategory}.";
Here it would have been nice if I can include the logic to determine the age category within the interpolated string. But Newlines inside a non-verbatim interpolated string are not supported in C# 10.0.

With C# 11.0, we now have the support for Newlines in String Interpolation Expressions. So I can simplify the code as follows.
int age = 60;
string message = $"Based on the Age of {age}, you are a(n) {age switch
{
< 1 => "Infant",
< 12 => "Child",
< 17 => "Adolescent",
< 65 => "Adult",
_ => "Older adult"
}}.";
Isn't it nice? There is no pleasure like having readable simplified code.

Read more of C# features here.
   What's new in C# 11

Happy Coding.

Regards,
Jaliya

No comments:

Post a Comment