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

后端 未结 1 1707
梦谈多话
梦谈多话 2021-02-20 18:19

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 righ

1条回答
  •  南方客
    南方客 (楼主)
    2021-02-20 18:49

    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.

    0 讨论(0)
提交回复
热议问题