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?
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?
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.
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.
it really depends on what you need. Generally, if you need to concat strings, the best performance in runtime will be achieved by using StringBuilder. If you're referring in source code something like var str = "String1"+"String2" it will be converter into string str = "String1String2" on compilation. In this case you have no concatenation overhead
If the whitespace isn't important then you can use the @ escape character to write multi-line strings in your code. This is useful if you have a query in your code for example:
string query = @"SELECT whatever
FROM tableName
WHERE column = 1";
This will give you a string with line breaks and tabs, but for a query that doesn't matter.
StringBuilder is a good way to go if you have many (more than about four) strings to concatenate. It's faster.
Using String.Concat in you example above is done at compile time. Since they are literal strings they are optimized by the compiler.
If you however use variables:
string a = "string1";
string b = "string2";
string c = a + b;
This is done at runtime.
StringBuilder will be your fastest approach if you are using any amount of strings.
http://dotnetperls.com/Content/StringBuilder-1.aspx
If you are just doing a few string (5 or less is a good rule) the speed will not matter of what kind of concatenation you are using.