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.