String output: format or concat in C#?

前端 未结 30 1621
一生所求
一生所求 2020-11-22 11:40

Let\'s say that you want to output or concat strings. Which of the following styles do you prefer?

  • var p = new { FirstName = \"Bill\", LastName = \"Ga

30条回答
  •  隐瞒了意图╮
    2020-11-22 12:15

    Starting from C# 6.0 interpolated strings can be used to do this, which simplifies the format even more.

    var name = "Bill";
    var surname = "Gates";
    MessageBox.Show($"Welcome to the show, {name} {surname}!");
    

    An interpolated string expression looks like a template string that contains expressions. An interpolated string expression creates a string by replacing the contained expressions with the ToString represenations of the expressions’ results.

    Interpolated strings have similar performance to String.Format, but improved readability and shorter syntax, due to the fact that values and expressions are inserted in-line.

    Please also refer to this dotnetperls article on string interpolation.

    If you are looking for a default way to format your strings, this makes sense in terms of readability and performance (except if microseconds is going to make a difference in your specific use case).

提交回复
热议问题