Best way to break long strings in C# source code

后端 未结 10 1435
伪装坚强ぢ
伪装坚强ぢ 2021-02-03 18:47

I am wondering what is the \"best practice\" to break long strings in C# source code. Is this string

\"string1\"+
\"string2\"+
\"string3\"

con

相关标签:
10条回答
  • 2021-02-03 19:41

    Your example will be concatenated at compile time. All inline strings and const string variables are concatenated at compile time.

    Something to keep in mind is that including any readonly strings will delay concatting to runtime. string.Empty and Environment.NewLine are both readonly string variables.

    0 讨论(0)
  • 2021-02-03 19:41

    Can't you use a StringBuilder?

    0 讨论(0)
  • 2021-02-03 19:44

    There´s any way to do it. My favorete uses a string´s method´s from C#. Sample One:

    string s=string.Format("{0} {1} {0}","Hello","By"); result is s="Hello By Hello";

    0 讨论(0)
  • 2021-02-03 19:46

    It's done at compile time. That's exactly equivalent to "string1string2string3".

    Suppose you have:

    string x = "string1string2string3"
    string y = "string1" + "string2" + "string3"
    

    The compiler will perform appropriate interning such that x and y refer to the same objects.

    EDIT: There's a lot of talk about StringBuilder in the answers and comments. Many developers seem to believe that string concatenation should always be done with StringBuilder. That's an overgeneralisation - it's worth understanding why StringBuilder is good in some situations, and not in others.

    0 讨论(0)
提交回复
热议问题