C# 11: Raw String Literals or Better @Verbatim strings

Verbatim string in pre-C# 11, allowed developers to, with many escape characters, to get a raw string with formatting, but the strings were hard to read.

Here’s how to transition to the much easier to read

Step 1: No more escaped characters. Raw String Literals are any text inside of a set of 3 double quotes. In this below example a json string looks beautiful and has no escaped characters:

			var rawString = """
				{
				      "religion": "Baha'i",
				      "global": true,
				      "genderEquality": true,
				      "priesthood": false      
				}  
                """;

Step 2: Now that we have easy-to-read text, we can use $ to put support interpolation:

			bool isGlobalReligion = true;
			var rawString = $$"""
				{
				      "religion": "Baha'i",
				      "global": true,
				      "genderEquality": true,
				      "priesthood": false,
					  "isGlobal": {{isGlobalReligion}}
				}  
				""";

The number of $ matter, the number of $ that are prefixed is the number of curly brackets that indicate a nested code expression. This means that a $ behaves just like the existing string interpolation – a single set of curly brackets.

Leave a comment