- by gowthamk91
Introduction:
Almost 15 new features have been released with C# 11. In this series we will be exploring all the new features in C#11. In this blog I’m going to explore Raw String Literals.
Raw String Literals:
This feature brings more friendliness in the code to handle the double quotes and other special characters within a string, which means the raw string literal contains new line, whitespaces, quotes and other special character without requiring escape sequences.
Before C# 11 :
var str = "<input text=\"Text\">";
Console.WriteLine(str);
From the above code it’s quite obvious, we are using escape sequence to handle the quote in the string.
In C# 11:
var str = """<input text="Text">"""; // raw string literal
Console.WriteLine(str);
Now a raw string literal uses three double quotes on a start of the string and end of the string respectively.
Assume if the “Text” has two more double quote, in this case we should add one more double quote on a start and end of the string respectively and so on, as given below.
var str = """"<input text="""Text""">"""";
Console.WriteLine(str);
Personally, it’s one of my favorite features, because it will super easy to handle the JSON string in C# with Raw string literals.
Before C# 11:
var jsonStr = "{\n \"name\":\"Gowtham\" \n}";
Console.WriteLine(jsonStr);
The problem with the above JSON string is it’s very unfriendly where it has a escape sequence to handle the new line and a double quotes . Let’s see how to replace it with raw string literals.
In C# 11:
var jsonStr = """
{
"name":"Gowtham"
}
""";
Console.WriteLine(jsonStr);
The above JSON string is very super friendly to write with raw string literals.
Summary:
We have seen how to use the raw string literals in our code and how to replace the escapes sequences using the raw string literals. It brings a developer 🧑💻 friendliness while writing a code. We will see more about C# 11 features in my next blog
Happy Coding!!!