111

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Matt
  • 1,109
  • 2
  • 7
  • 4
  • Thanks. But then I cant use string interpolation? I don't want to escape everything. I just want to use a backslash inside of an interpolated string. – Matt Jul 10 '15 at 05:31
  • No you can't. His answer is wrong. – greenhoorn Jul 10 '15 at 05:32
  • 3
    feels like a bug to me ;) \\ should work – Matt Jul 10 '15 at 05:37
  • I get the correct output for ${domain}\\{userName}.. Is it a web application? – greenhoorn Jul 10 '15 at 05:37
  • you mean something like **string.format("{0}\\{1}", domain, userName);** or **string.format(@"{0}\{1}", domain, userName);** – Дмитрий Чистик Jul 10 '15 at 05:39
  • console app. Console.WriteLine($"{DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss")} Writing record for {domainstring}\\{UserName}" ); – Matt Jul 10 '15 at 05:39
  • @ДмитрийЧистик Yes he is using the short version of string interpolation.. I don't know why yours doesn't work, I exactly did the same in my console application and it works. – greenhoorn Jul 10 '15 at 05:41
  • I don't want to use string.format I want to use the new string interpolation feature of c# 6. Notice in my code I don't have any value place holders in the curly braces or variables after the string. the values are essentially interpolated on the fly in c# 6 – Matt Jul 10 '15 at 05:42
  • String interpolation should work for `\\`. That's how you escape a single backslash. – Yuval Itzchakov Jul 10 '15 at 06:58
  • 2
    Nhan's answer seems to work perfectly. `$@"{domain}\{userName}"`. I think you should try it, and accept it. I had exactly the same problem, down to it also being domain and user name, and his method works fine. – ProfK Dec 29 '16 at 07:25
  • any update here for c# 8.0 ? – Alex Gordon May 21 '19 at 17:31

7 Answers7

136

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
birdamongmen
  • 1,940
  • 1
  • 15
  • 12
104

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Nhan
  • 1,405
  • 1
  • 13
  • 16
  • 4
    The best and simple answer. Don't understand why people choose more complicated answers. MSDN link for verbatim interpolated strings https://learn.microsoft.com/en-us/dotnet/csharp/tutorials/string-interpolation#how-to-use-escape-sequences-in-an-interpolated-string – Alex34758 Oct 12 '18 at 08:24
  • 5
    "Starting with C# 8.0, you can use the $ and @ tokens in any order" (From Alex's link in the above comment). – Casey Plummer Oct 05 '19 at 15:05
17

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Dirk Strauss
  • 630
  • 1
  • 8
  • 19
  • 3
    The OP isn't trying to escape curly braces. They clearly state they are trying to escape a backslash itself, and the normal `\\\` doesn't work in an interpolated string. – ProfK Dec 29 '16 at 06:20
  • 4
    I don't care what OP was asking I wanted to escape curly braces and first google entry was this. So OP heading mislead google and this is therefore a valid answer and deserves upvoting. – AndrewBenjamin May 24 '19 at 02:26
5
$"{domain}\\{user}"

Works fine - escaping works as usual (except when escaping {). At least on .NET 4.6 and Visual Studio 14.0.22823 D14REL.

If it doesn't work for some reason (maybe you're using an older version of the compiler?), you could also try being more explicit:

$"{domain}{@"\"}{user}"
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Luaan
  • 62,244
  • 7
  • 97
  • 116
  • That's what I thought too. interesting, on my surface pro 3, the code works fine with either the normal \\ or explicit @"\", however on my work machine it does not. so I think you may have hit the nail on the head with regards to the version installed. My work machine is saying no updates are available, unfortunately. So, my question to you is how do I determine the exact version/build of .net 4.6 on my machine? things seem to have changed a bit in this regard an im not able to find much guidance on build/version numbers. – Matt Jul 12 '15 at 23:09
  • from what I can tell I am running the same version of .net and vs 2015 RC on both machines. the only difference I can think of is that the machine that is working as expected (SP3) is running the latest insider preview of windows 10. I believe .net framework comes with this, so maybe I have a newer version there somehow. I just don't know how to check specifically though. – Matt Jul 12 '15 at 23:24
  • **UPDATE** looking in the c:\windows\microsoft.net\framework64\v4.0.30319 folder at the property details for clr.dll I can see a difference. the version on my surface is 4.6.79.0 and the version on my work machine is 4.6.57.0. So my question is now, how do I upgrade from 4.6.57.0 to 4.6.79.0? (why is this sooo hard! ;) – Matt Jul 12 '15 at 23:29
  • @Matt I don't think that's it - I also have 4.6.57.0 and it works fine. Is it possible you have some Visual Studio extension installed that messes things up? – Luaan Jul 13 '15 at 07:00
  • In case you observe a difference in behavior despite not seeing any updates perhaps consider the use of the NuGet package "Microsoft.Net.Compilers" in the projects that use the latest C# features. This may resolve the observed differences in behavior. It did in our projects. – Manfred May 27 '17 at 21:21
3

The rule for escape the backslash in an interpolated string is to duplicate the backslash:

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

Console output

But if you also use the interpolated string as a verbatim string then you don't need to escape the backslash:

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

And you get the same:

Console output

For a tutorial about interpolated strings (in Spanish): see a video about interpolated strings

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
freedeveloper
  • 3,670
  • 34
  • 39
-1

If I did not misunderstand, the solution is real simple:

var domain = "mydomain";
var userName = "myUserName";
var combo = $"{{{domain}}}\\{{{userName}}}";
Console.WriteLine(combo);

I share birdamongmen's answer as well as the good reference provided there.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Eduardo
  • 85
  • 5
  • 2
    You did misunderstand. The OP isn't trying to escape curly braces. They clearly state they are trying to escape a backslash itself, and the normal `\\\` doesn't work in an interpolated string – ProfK Dec 29 '16 at 06:21
-5

You can use this -

' First, declare the curly brackets as chars
Dim LeftBrace As Char = "{"
Dim RightBrace As Char = "}"

' Then in your string, use it like this:
Dim myStr As String = $"This is a {LeftBrace}String{RightBrace}"

' Now, the output will be
' This is a {string}code here
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Vinod KC
  • 29
  • 2
  • 9