How do I interpolate strings?

前端 未结 15 762
感情败类
感情败类 2020-11-27 05:38

I want to do the following in C# (coming from a Python background):

strVar = \"stack\"
mystr  = \"This is %soverflow\" % (strVar)

How do I

15条回答
  •  [愿得一人]
    2020-11-27 05:55

    This has been added as of C# 6.0 (Visual Studio 2015+).

    Example:

    var planetName = "Bob";
    var myName = "Ford"; 
    var formattedStr = $"Hello planet {planetName}, my name is {myName}!";
    // formattedStr should be "Hello planet Bob, my name is Ford!"
    

    This is syntactic sugar for:

    var formattedStr = String.Format("Hello planet {0}, my name is {1}!", planetName, myName);
    

    Additional Resources:

    String Interpolation for C# (v2) Discussion

    C# 6.0 Language Preview

提交回复
热议问题