I want a C# 4 string constant to represent a new line and a tab as in the following:
internal const string segment = "\r\n\t";
I know there is Environment.Newline which I guess I could use like this:
internal const string segment = Environment.NewLine + "\t";
My question is what is the most efficient way to construct a string constant that has a new line and a tab?
Provided you declare the string as
const, as above, there is absolutely no difference in terms of efficiency. Any constant will be substituted at compile time and use an interned string.Unfortunately, the second option is not a compile time constant, and will not compile. In order to use it, you’d need to declare it as:
I, personally, find this very clear in terms of intent, and it would be my preference, even though it’s not going to be a compile time constant. The extra overhead/loss of efficiency is so incredibly minor that I would personally choose the clear intent and legible code over the compile time constant.
Note that using
Environment.NewLinealso has the benefit of being correct if you port this code to Mono, and your goal is to use the current platforms line separator. The first will be incorrect on non-Windows platforms in that specific case. If your goal is to specifically include"\r\n\t", and do not desire the platform-specific line separator, thenEnvironment.NewLinewould be an inappropriate choice.