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

2020-07-06 05:07发布

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条回答
冷血范
2楼-- · 2020-07-06 05:36

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.

查看更多
登录 后发表回答