0

I have a strange situation. When I do a string verbatim like this:

string str = @"Hello 
World"

The string is created with a "\r\n" so that it's "Hello \r\nWorld". I want it to be created with just the new line, no carriage return so that it's "\n" only.

Now, I realize I can do:

str = str.Replace("\r", "")

But the string is a const variable specifically because I don't want a whole lot of instantiations and manipulations for performance (no matter how small), etc

Anyone know how I could do this so that, I could write a many line text stored as a const string with no "\r" that still appears formatted and easy to read in code?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Tamer Rifai
  • 169
  • 2
  • 14
  • 1
    This depends on the editor you're using. If the **file** contains a carriage return, then that's what you will get. – Lasse V. Karlsen Apr 24 '20 at 20:46
  • 4
    You'll need to be careful with your source control settings. If you have newline translation (autocrlf) enabled in Git, your LF-only lines could be changed to CR/LF. – madreflection Apr 24 '20 at 20:48
  • Is it not possible to write the string as `"Hello \nWorld"`? Even if it means a little bit more work? – Andrew Morton Apr 24 '20 at 20:55

1 Answers1

1

It's your editor doing this to you, not C#.

If you take a look at your code in a hex editor, you'll see that the line "string str = @"Hello " ends with \r\n, not with just \n.

On Windows, by default, return is two characters \r\n, not just one like it is on Mac \n.

Most editors have an option to change this. However, eventually something's going to switch the file back to using \r\n on you when you're not looking.

The language doesn't provide a clean way around this. Just use a non-verbatim string or do a replace.

Merkle Groot
  • 846
  • 5
  • 9