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

我的未来我决定 提交于 2019-11-27 22:38:41
birdamongmen

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.

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

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

Works fine - escaping works as usual (except when escaping {). At least on .NET 4.6 and VS 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}"

Hi the rule for escape the back slash in interpolated string is duplicate the back slash:

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

but if you also use the interpolated string as verbatim string then you don't need to escape the back slash:

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

and you get the same:

For a tutorial about interpolated string: see video interpolated string

If I did not missunderstood. The solution is real simple

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

I share the birdamongmen answer as well good reference provided there. Hope it is helpfull to you. My 5 cents

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!