C# 11 New Feature - Raw String Literals

Raymond Raymond event 2022-04-22 visibility 492
more_vert
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

More from Kontext
comment Comments
No comments yet.

Please log in or register to comment.

account_circle Log in person_add Register

Log in with external accounts