Saturday, 15 October 2022

No More " Escaping Needed with C# 11

Writing json body in C# code as a string variable value to pass on to a method or service, is something you may hate as you need to escape every " that you use in your json specification, even though you could use @ (verbatim string literals) to write multi-line strings.  With new Raw String Literals in c# 11, we can write " as content of the strings wihtout having to escape each instance. Let's explore bit about escaping double qutes with Raw String Literals.

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.

Even if you use two consective ", they will be 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:

Popular Posts