Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String constant for a new line + tab?

Tags:

string

c#

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?

like image 385
syneptody Avatar asked Dec 15 '11 18:12

syneptody


People also ask

How do you write a string constant?

A string constant is enclosed in double quotation marks ("). Any ASCII character is a valid character in a constant string.

What is string constant example?

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.

Can strings be constant?

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."


2 Answers

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.

like image 91
Reed Copsey Avatar answered Oct 07 '22 15:10

Reed Copsey


const won't work. use static readonly.

internal static readonly string segment = Environment.NewLine + "\t"; 
like image 39
Daniel A. White Avatar answered Oct 07 '22 17:10

Daniel A. White