Skip to content

Commit

Permalink
CSharp string literals (#7453)
Browse files Browse the repository at this point in the history
* Added raw string literals example

* Remove .idea folder

* Explained white space better
  • Loading branch information
danielmackay authored Dec 6, 2023
1 parent 3b94db3 commit bd2e21f
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
.DS_Store
.vscode/settings.json
.idea
36 changes: 36 additions & 0 deletions rules/how-string-should-be-quoted/rule.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ created: 2018-04-30T22:20:15.0000000Z
authors:
- title: Adam Cogan
url: https://ssw.com.au/people/adam-cogan
- title: Daniel Mackay
url: https://ssw.com.au/people/daniel-mackay
related: []
redirects:
- c-code-do-you-use-string-literals
Expand All @@ -34,3 +36,37 @@ string p2 = @"\My Documents\My Files\";
::: good
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.

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

::: bad
Figure: Bad example - Single quotes
:::

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

::: good
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](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/raw-string)

0 comments on commit bd2e21f

Please sign in to comment.