DEV Community

Juarez Júnior for Develop4Us

Posted on • Edited on

C# Tip: Raw String Literals with Interpolation

Let’s talk about Raw String Literals with Interpolation, introduced in C# 11, which allow you to work with strings more cleanly by eliminating the need for escaping special characters like quotes and slashes, while also enabling interpolation within these strings. See the example in the code below.

string name = "John";
int age = 30;

string json = $$"""
{
    "Name": "{{name}}",
    "Age": {{age}}
}
""";

Console.WriteLine(json);
Enter fullscreen mode Exit fullscreen mode

Explanation:

In C# 11, you can use Raw String Literals to write strings that contain many special characters, such as double quotes or backslashes, without needing to escape them. This greatly simplifies the code, especially when dealing with file paths, JSON, or other text formats.

Additionally, you can interpolate variables within these raw strings, allowing you to easily format the content. In the example above, we use a raw string to represent JSON and interpolate a variable inside it, making the output more readable and easier to write.

Source code: GitHub

I hope this tip helps you use Raw String Literals to simplify your string work in your projects! Until next time.

Top comments (0)