Is it possible to include a C# variable in a string variable without using a concatenator?

前端 未结 14 1796
遥遥无期
遥遥无期 2021-02-14 07:02

Does .NET 3.5 C# allow us to include a variable within a string variable without having to use the + concatenator (or string.Format(), for that matter).

For example (In

14条回答
  •  花落未央
    2021-02-14 07:37

    string.Format (and similar formatting functions such as StringBuilder.AppendFormat) are the best way to do this in terms of flexibility, coding practice, and (usually) performance:

    string s = string.Format("The date is {0}", d);
    

    You can also specify the display format of your DateTime, as well as inserting more than one object into the string. Check out MSDN's page on the string.Format method.

    Certain types also have overloads to their ToString methods which allow you to specify a format string. You could also create an extension method for string that allows you to specify a format and/or parse syntax like this.

提交回复
热议问题