String output: format or concat in C#?

前端 未结 30 2036
一生所求
一生所求 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:12

    I choose based on readability. I prefer the format option when there's some text around the variables. In this example:

    Console.WriteLine("User {0} accessed {1} on {2}.", 
                       user.Name, fileName, timestamp);
    

    you understand the meaning even without variable names, whereas the concat is cluttered with quotes and + signs and confuses my eyes:

    Console.WriteLine("User " + user.Name + " accessed " + fileName + 
                      " on " + timestamp + ".");
    

    (I borrowed Mike's example because I like it)

    If the format string doesn't mean much without variable names, I have to use concat:

       Console.WriteLine("{0} {1}", p.FirstName, p.LastName);
    

    The format option makes me read the variable names and map them to the corresponding numbers. The concat option doesn't require that. I'm still confused by the quotes and + signs, but the alternative is worse. Ruby?

       Console.WriteLine(p.FirstName + " " + p.LastName);
    

    Performance wise, I expect the format option to be slower then the concat, since format requires the string to be parsed. I don't remember having to optimize this kind of instruction, but if I did, I'd look at string methods like Concat() and Join().

    The other advantage with format is that the format string can be put in a configuration file. Very handy with error messages and UI text.

提交回复
热议问题