Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

357
Views
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?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report

0

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.

over 4 years ago · Santiago Trujillo Report

0

Eduardo is correct. You escape curly braces by doubling up. Therefore, if you wanted to output the domain variable as {mydomain} you would need to do:

$"{{{domain}}}";

Furthermore, assuming that the current date is 1 Sept 2016, doing this:

$"The date is {DateTime.Now}";

would output something like "The date is 2016/09/01 3:04:48 PM" depending on your localization. You can also format the date by doing:

$"The date is {DateTime.Now : MMMM dd, yyyy}";

which would output "The date is September 1, 2016". Interpolated strings are much more readable. Good answer Eduardo.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!