C# Raw string literals

Before raw string literals

The main problems with long string literals were:

  • strings that include double quotes tend to be unreadable
  • identation looks messy in multiline strings

we have the following json we want to put into a string literal

{
	"number": 42,
	"text": "Hello, world",
	"nested": { "flag": true}
}

an ordinary quoted string literal looks like this:

string json = "{\r\n  \"number\": 42,\r\n  \"text\": \"Hello, world\",\r\n  \"nested\": { \"flag\": true }\r\n}"

verbatim string literals work slightly better here but will be missaligned when used over nested code. Also quotes look different as they still need to be scaped.

foreach(var item in list)
{
	if(Check(item))
	{
		string json = @"{
  ""number"": 42,
  ""text"": ""Hello, world"",
  ""nested"": { ""flag"": true }
}";
	}
}

Using raw string literals

Here’s how this example looks using raw literals.

foreach(var item in list)
{
	if(Check(item))
	{
		string json = """
		{
			"number": 42,
			"text": "Hello, world",
			"nested": { "flag": true }
		}
		""";
	}
}

Inside raw literals we don’t need to scape chars. Also we’re able to indent our code.

Interpolate raw string literals

This is also possible

foreach(var item in list)
{
	if(Check(item))
	{
		string json = $"""
		{
			"number": {item.Number},
			"text": "Hello, world",
			"nested": { "flag": true }
		}
		""";
	}
}

If you don’t need to put any braces {} inside the interpolated string, you may use $ to indicate this is an interpolate string, but what happens when you need to use {} for anything else?
Then you use $$ to indicate this is an interpolate string and the compiler will use two braces to indicate for an interpolated string. If you need to use two braces then you use $$$ and }, and so on.

Reference(s)

https://endjin.com/blog/2023/02/dotnet-csharp-11-raw-string-literals