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?
A string constant is enclosed in double quotation marks ("). Any ASCII character is a valid character in a constant string.
A string constant is an arbitrary sequence of characters that are enclosed in single quotation marks (' '). For example, 'This is a string'. You can embed single quotation marks in strings by typing two adjacent single quotation marks.
String constants, also known as string literals, are a special type of constants which store fixed sequences of characters. A string literal is a sequence of any number of characters surrounded by double quotes: "This is a string."
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:
internal static readonly string segment = Environment.NewLine + "\t";
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.NewLine
also 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, then Environment.NewLine
would be an inappropriate choice.
const
won't work. use static readonly
.
internal static readonly string segment = Environment.NewLine + "\t";
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