What does '$' sign do in C# 6.0?

怎甘沉沦 提交于 2019-12-09 15:15:47

问题


In MVC 6 source code I saw some code lines that has strings leading with $ signs.

As I never saw it before, I think it is new in C# 6.0. I'm not sure. (I hope I'm right, otherwise I'd be shocked as I never crossed it before.

It was like:

var path = $"'{pathRelative}'";

回答1:


You're correct, this is a new C# 6 feature.

The $ sign before a string enables string interpolation. The compiler will parse the string specially, and any expressions inside curly braces will be evaluated and inserted into the string in place.

Under the hood it converts to the same thing as this:

var path = string.Format("'{0}'", pathRelative);

Let's look at the IL for this snippet:

var test = "1";
var val1 = $"{test}";
var val2 = string.Format("{0}", test);

Which compiles to:

// var test = "1";
IL_0001: ldstr "1"
IL_0006: stloc.0

// var val1 = $"{test}";
IL_0007: ldstr "{0}"
IL_000c: ldloc.0
IL_000d: call string [mscorlib]System.String::Format(string, object)
IL_0012: stloc.1

// var val2 = string.Format("{0}", test);
IL_0013: ldstr "{0}"
IL_0018: ldloc.0
IL_0019: call string [mscorlib]System.String::Format(string, object)
IL_001e: stloc.2

So the two are identical in the compiled application.


A note on the C# string interpolation syntax: Unfortunately the waters are muddied right now on string interpolation because the original C# 6 preview had a different syntax that got a lot of attention on blogs early on. You'll still see a lot of references to using backslashes for string interpolation, but this is no longer syntactically valid.



来源:https://stackoverflow.com/questions/30194893/what-does-sign-do-in-c-sharp-6-0

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