Escape sequences with String Interpolation

338 views Asked by At

Using C# 6 I have the following:

$"\{wordSeparator}+"

This does not compile because of \ so I tried:

$"\\{wordSeparator}+"

This compiles but when I ran my code I got the error:

Unrecognized escape sequence \\

How can I solve this?

2

There are 2 answers

2
SLaks On

Read the error message from your first example:

CS8087: A '{' character may only be escaped by doubling '{{' in an interpolated string.

0
mm8 On

"wordseparator" is supposed to be a variable. This works:

string wordSeparator = "\\";
string s = $"\\{wordSeparator}+";

If "wordseparator" is not a variable but part of the string you should escape the '{' as well:

string s = $"\\{{wordSeparator}}+";