According to the article "How to: Concatenate Multiple Strings (C# Programming Guide)" string literals and string constants will be concatentated into a single string at compile time. It further states that string variables can only be concatenated at run time.
I have string literals and enum value constants only, but I do have a slightly more complex scenario where these are combined with two static method calls. For readability and convenience purposes I declare a static string containing SQL as per the below example:
private enum StatGroup
{
Test,
...
}
private static string TestSql =
Regex.Replace(
String.Format(
@"INSERT INTO StatCounts (StatGroup, LinkStatus, LinkCount)
SELECT '{0}', LinkStatus, COUNT(*)
FROM LinkInfo
GROUP BY LinkStatus",
StatGroup.Test),
@"\s+", " ", RegexOptions.Multiline),
I use String.Format(), so that I can utilize the enum for inserting valid value values into the StatGroup
table column. I use Regex to remove the unnecessary whitespace in the SQL script. The whitespace is not required at run time, but serves well for readability of the code.
Is the compiler smart enough to optimize the above at compile time?
No, those are run-time function calls. String concats of literals are easy for the compiler to join at compile time, but RegEx and string.Format are more complex and are run-time only. String concat of literals is the special case.