I am wondering what is the "best practice" to break long strings in C# source code. Is this string
"string1"+ "string2"+ "string3"
concatenated during compiling or in run time?
Another way of splitting a string literal is to set the caret where you want to split the string, press Alt+Enter and choose Split string.
We can use string literal concatenation. Multiple string literals in a row are joined together: char* my_str = "Here is the first line." "Here is the second line."; But wait!
Use triple quotes to create a multiline string It is the simplest method to let a long string split into different lines. You will need to enclose it with a pair of Triple quotes, one at the start and second in the end. Anything inside the enclosing Triple quotes will become part of one multiline string.
C++ ignores whitespace so the line will go on until you terminate it with a semicolon.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With