C# Code - Do you use string literals?
Updated by Brady Stroud [SSW] 1 year ago. See history
123
<introEmbed body={<> 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](<https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2008/c84eby0h(v=vs.90?WT.mc_id=DT-MVP-33518)?redirectedfrom=MSDN>) </>} /> ```cs string p2 = "\\My Documents\\My Files\\"; ``` <figureEmbed figureEmbed={{ preset: "badExample", figure: 'Figure: Bad example - Using "\\"', shouldDisplay: true } } /> ```cs string p2 = @"\My Documents\My Files\"; ``` <figureEmbed figureEmbed={{ preset: "goodExample", figure: 'Figure: Good example - Using @', shouldDisplay: true } } /> ## 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. ```cs var bad = "<html>" + "<body>" + "<p class=\"para\">Hello, World!</p>" + "</body>" + "</html>"; ``` <figureEmbed figureEmbed={{ preset: "badExample", figure: 'Figure: Bad example - Single quotes', shouldDisplay: true } } /> ```cs var good = """ <html> <body> <p class="para">Hello, World!</p> </body> </html> """; ``` <figureEmbed figureEmbed={{ preset: "goodExample", figure: 'Figure: Good example - Using raw string literals', shouldDisplay: true } } /> For more information on Raw String literals see [learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/raw-string](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/raw-string?WT.mc_id=DT-MVP-33518)
Categories
Related rules
Need help?
SSW Consulting has over 30 years of experience developing awesome software solutions.