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

Matt picture Matt · Jul 10, 2015 · Viewed 56.5k times · Source

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

What I want is something like this..

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

I want the output of combo to be

myDomain\myUserName

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

How can I include escaped characters in an interpolated string?

Answer

birdamongmen picture birdamongmen · Mar 22, 2016

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 https://msdn.microsoft.com/en-us/library/dn961160.aspx.

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