C# 11 New Feature - Raw String Literals

visibility 41 access_time 29 days ago languageEnglish timeline Stats
C# 11 New Feature - Raw String Literals

In previous version of C#, it is not convenient to create string literals that have double quotes or HTML, XML in it. In C# 11, raw string literal feature is added so that C# developers can now use """ to create raw string literals like Python developers. 

Prior to C# 11

Previously, we use \ to escape quotes in a string literal like the following code snippet shows:

using System;
					
public class Program
{
	public static void Main()
	{
		var str = "I have a double quote (\")";
		Console.WriteLine(str);
	}
}

Alternatively, we can also use @ to specify a string without escape.

using System;
					
public class Program
{
	public static void Main()
	{
		var str = @"I have a double quote ("")";
		Console.WriteLine(str);
	}
}

The output are all the same:

I have a double quote (")

C# 11 raw string literal

The above example can be simply implemented in C# 11:

using System;
					
public class Program
{
	public static void Main()
	{
		var str = """I have a double quote (")""";
		Console.WriteLine(str);
	}
}

Multiline string literal

You can also use it to implement multi-line string literal:

var str = """I have a double quote (")
			
			another line
			""";

String interpolation 

You can also use string interpolation together with raw string literal. The number of $ that prefixes the string is the number of curly brackets that are required to indicate a nested code expression.

var var1 = 1;
var jsonString = $$"""
{
  "attr1": {{var1}},
  "attr2": "{1,2,3,4,5}"
}
""";

In the above example, {{var1}} interpolation string will be replaced with value 1.

Enjoy this new feature of C# 11. It makes C# programming even more efficient now. 

References

C# 11 Preview Updates - Raw string literals, UTF-8 and more! - .NET Blog

copyright This page is subject to Site terms.

Please log in or register to comment.

account_circle Log in person_add Register

Log in with external accounts

More from Kontext
C# Regex - Remove Heading Tags
visibility 328
thumb_up 0
access_time 2 years ago
Convert string to date in C# / .NET Framework
visibility 264
thumb_up 0
access_time 2 years ago
Load Fonts as Glyph in .NET
visibility 37
thumb_up 0
access_time 2 months ago
Load Fonts as Glyph in .NET