SSW Foursquare

C# Code - Do you use string literals?

Last updated by Daniel Mackay [SSW] 5 months ago.See history

Do you know String should be @-quoted instead of using escape character for "\"? The @ symbol specifies that escape characters and line breaks should be ignored when the string is created.

As per: Strings

string p2 = "\\My Documents\\My Files\\";

Figure: Bad example - Using "\"

string p2 = @"\My Documents\My Files\";

Figure: Good example - Using @

Raw String Literals

In C#11 and later, we also have the option to use raw string literals. These are great for embedding blocks of code from another language into C# (e.g. SQL, HTML, XML, etc.). They are also useful for embedding strings that contain a lot of escape characters (e.g. regular expressions).

Another advantage of Raw String Literals is that the redundant whitespace is trimmed from the start and end of each line, so you can indent the string to match the surrounding code without affecting the string itself.

var bad = "<html>" +
           "<body>" +
           "<p class=\"para\">Hello, World!</p>" +
           "</body>" +
           "</html>";

Figure: Bad example - Single quotes

var good = """
           <html>
           <body>
           <p class="para">Hello, World!</p>
           </body>
           </html>
           """;

Figure: Good example - Using raw string literals

For more information on Raw String literals see learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/raw-string

We open source. Powered by GitHub