Raw String Literals In C# 11

Here’s another one from the vault of “Huh, I guess I never thought I needed that until now”

Recently I was trying to write a unit test that required me to paste in some known JSON to validate against. Sure, I could load the JSON from a file, but I really don’t like File IO in unit tests. What it ended up looking like was something similar to :

var sample = "{\"PropertyA\":\"Value\"}";

Notice those really ugly backslashes in there trying to escape my quotes. I get this a lot when working with JSON or even HTML string literals and my main method for getting around it is loading into notepad with a quick find and replace.

Well, starting from C# 11, you can now do the following!

var sample = """
{"PropertyA":"Value"}
""";

Notice those (ugly) three quote marks at the start and end. That’s the new syntax for “Raw String Literals”. Essentially allowing you to mix in unescaped characters without having to start backslashing like a madman.

Also supported is multi line strings like so :

var sample = """
{
    "PropertyA" : "Value"
}
""";

While this feature is officially coming in C# 11 later this year, you can get a taste for it by adding the following to your csproj file.

<LangVersion>preview</LangVersion>

I would say that editor support is not all too great now. The very latest Visual Studio 2022 seems to handle it fine, however inside VS Code I did have some issues (But it still compiled just fine).

One final thing to note is about the absence of the “tick” ` character. When I first heard about this feature, I just assumed it would use the tick character as it’s pretty synonymous with multi line raw strings (atleast in my mind).

With the final decision being

In keeping with C# history, I think " should continue to be the string literal delimiter

I’m less sure on that. I can’t say that three quote marks makes any more sense than a tick, especially when it comes to moving between languages so… We shall see if this lasts until the official release.

Leave a Comment