SSW Foursquare

C# Code - Do you use string literals?

Last updated by Daniel Mackay [SSW] 3 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>" +

Figure: Bad example - Single quotes

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

Figure: Good example - Using raw string literals

For more information on Raw String literals see

We open source. Powered by GitHub