c# string formatting

前端 未结 13 1566
离开以前
离开以前 2020-12-25 14:12

I m curious why would i use string formatting while i can use concatenation such as

Console.WriteLine(\"Hello {0} !\", name);

Console.WriteLine(\"Hello \"+          


        
13条回答
  •  北荒
    北荒 (楼主)
    2020-12-25 14:40

    There isn't a singular correct answer to this question. There are a few issues you want to address:

    Performance

    The performance differences in your examples (and in real apps) are minimal. If you start writing MANY concatenations, you will gradually see better memory performance with the formatted string. Refer to Ben's answer

    Readability

    You will be better off with a formatted string when you have formatting, or have many different variables to stringify:

    string formatString = "Hello {0}, today is {1:yyyy-MM-dd}";
    Console.WriteLine(formatString, userName, Date.Today);
    

    Extensibility

    Your situation will determine what's best. You tell me which is better when you need to add an item between Username and Time in the log:

    Console.WriteLine(
       @"Error! 
        Username: " + userName + "
        Time: " + time.ToString("HH:mm:ss") + "
        Function: " + functionName + "
        Action: " + actionName + "
        status: " + status + "
       ---");
    

    or

    Console.WriteLine(@"Error! 
        Username: {0}
        Time: {1}
        Function: {2}
        Action: {3}
        status: {4}
       ---",
        username, time.ToString("HH:mm:ss"), functionName, actionName, status);
    

    Conclusion

    I would choose the formatted string most of the time... But I wouldn't hesitate at all to use concatenation when it was easier.

提交回复
热议问题