Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to break long strings in C# source code

Tags:

string

c#

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?

like image 969
Alexander Prokofyev Avatar asked Nov 12 '08 10:11

Alexander Prokofyev


People also ask

How do you split a long string?

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.

How do I write a multi line string literal in C?

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!

How do you break a long string into multiple lines?

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.

How do you break a long line in C++?

C++ ignores whitespace so the line will go on until you terminate it with a semicolon.


1 Answers

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.

like image 120
Jon Skeet Avatar answered Oct 11 '22 10:10

Jon Skeet