Let's take below example of a json content written to console.
// Print json file to console
Console.WriteLine(
@"{
""name"": ""John"",
""age"": 30,
""cars"": [
""Ford"",
""BMW"",
""Fiat""
]
}");
As you can see above example we have to escape " in many places to ansure it prints as below in console.
Probabaly for a small example like this, implementation is easy. However, if your json is big enough wrting all these escapes are not that entertaining.
Now with C# 11 Raw String Literals you can write the same code in much neat and nice way, without having to escape the " in each occurance.
// Print json file to console
Console.WriteLine("""
{
"name": "John",
"age": 30,
"cars": [
"Ford",
"BMW",
"Fiat"
]
}
""");
Secret is using """ to begin and """ to end the string. Raw String literals need minimum of three double quotes.
Console.WriteLine("""Hello "World"!""");
This will print as below and " within string treated as content.
Console.WriteLine("""Hello ""World""!""");
Outputs
If you need more consecutive " in your string to be as content increase the number of of " used in the begining and end.
For example, when we have 5 double qoutes at begining and end, we can use consective 4 double quotes in the string.
Console.WriteLine("""""Hello """"World""""!""""");
Outputs
No comments:
Post a Comment