DEV Community

Kenichiro Nakamura
Kenichiro Nakamura

Posted on

C# 11: New raw string literals feature makes my life easier!

The best new feature of C# 11 for me is raw string literals.

In this post, I explain the scenario when I use the new feature.

Escape Double Quotation

I often use a JSON string in my unit tests to arrange mock data. The pain point was that I need to escape double quotation like this.

var json = @"
{
    ""key"":""value""
}
";
Enter fullscreen mode Exit fullscreen mode

With C# 11 new feature, I can use triple double quotations at the beginning and the end so that I don't need to escape it inside the content.

var json = """
{
    "key":"value"
}
""";
Enter fullscreen mode Exit fullscreen mode

If I need to use triple double quotation inside the content, I can add one more quotation.

Escape Curly Braces

When I create mock data, I often use variable in string format which uses curly braces. I also need to escape curly braces as JSON string uses curly braces. Before C# 11, it looks like this.

var json = $@"
{{
    ""key"":""{value}""
}}";
Enter fullscreen mode Exit fullscreen mode

With C# 11 new feature, I can add an additional dollar mark to indicate how many curly braces I use for string format, so that I don't need to escape the curly braces in the content.

var json = $$"""
{
   "key":"{{value}}"
}
""";
Enter fullscreen mode Exit fullscreen mode

Indentation

Indentation is important in C#, but I couldn't use indent as I wanted because if I use indent inside the JSON string, it was a part of content itself.

For example, I write a code snippet like this.

Console.WriteLine(JSON());

string JSON()
{
    return @"
    {
        ""key"":""value""
    }
    ";
}
Enter fullscreen mode Exit fullscreen mode

The result contains spaces.

result

With C# 11, I can write similar code.

Console.WriteLine(JSON());

string JSON()
{
    return """
    {
        "key":"value"
    }
    """;
}
Enter fullscreen mode Exit fullscreen mode

Then I have the expected result.

result

The closing """ indicate the starting line. So if I write code like below, I can include spaces.

Console.WriteLine(JSON());

string JSON()
{
    return """
        {
            "key":"value"
        }
    """;
}
Enter fullscreen mode Exit fullscreen mode

Visual Studio visualizes the line as well.

visual studio

Summary

I really love this feature and we all should start using this whenever we use JSON, XML or any other string we had to escape before.

Top comments (1)

Collapse
 
vercidium profile image
Vercidium

This is very useful! Thank you