Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use escape characters with string interpolation in C# 6?

I've been using string interpolation and love it. However, I have an issue where I am trying to include a backslash in my output, but I am not able to get it to work.

I want something like this...

var domain = "mydomain"; var userName = "myUserName"; var combo = $"{domain}\{userName}" 

I want the output of combo to be:

myDomain\myUserName 

I get a syntax error about the \ being an escape character. If I put in \\ then the syntax error is gone, but the output is myDomain\\myUsername.

How can I include escaped characters in an interpolated string?

like image 205
Matt Avatar asked Jul 10 '15 05:07

Matt


People also ask

How do you escape a string in interpolation?

Escape sequences Escaping backslash ( \ ) and quote ( " ) characters works exactly the same in interpolated strings as in non-interpolated strings, for both verbatim and non-verbatim string literals: Console. WriteLine($"Foo is: {foo}. In a non-verbatim string, we need to escape \" and \\ with backslashes.

Which character should be used for string interpolation?

To identify a string literal as an interpolated string, prepend it with the $ symbol. You can't have any white space between the $ and the " that starts a string literal. The expression that produces a result to be formatted.

How do you escape a character in a string?

\ is a special character within a string used for escaping. "\" does now work because it is escaping the second " . To get a literal \ you need to escape it using \ .

How do I add spaces to a string interpolation?

You can use string interpolation by using template literals; replace the quotes with backticks(`)(https://www.computerhope.com/jargon/b/backquot.htm). Hope this helped you on your coding journey! I am not sure why they are teaching this method, but you can just add a space between the quotation marks.


2 Answers

Escaping with a backslash(\) works for all characters except a curly brace.

If you are trying to escape a curly brace ({ or }), you must use {{ or }} per $ - string interpolation (C# reference)

... All occurrences of double curly braces (“{{“ and “}}”) are converted to a single curly brace.

like image 65
birdamongmen Avatar answered Sep 30 '22 21:09

birdamongmen


You can do this, using both the $@. The order is important.

var combo = $@"{domain}\{userName}"; 

The original question mentions specifically C# 6. As commented, C# 8 no longer cares for the order.

like image 28
Nhan Avatar answered Sep 30 '22 21:09

Nhan