Verbatim string is missing carriage return

770 Views Asked by At

I have encountered a strange issue today. I have a verbatim string like this:

var s = @"     0     1
0     0"

i.e. there is a new line after the one. My Environment.NewLine is set to \r\n

This is part of a unit test and the tests have been working fine for the past several months. Now when I run my tests the above string declaration is resulting in:

"     0     1\n     0     0"

instead of

"     0     1\r\n     0     0"

Meaning the tests fail.

I have dumped out every character to prove this is true. I have also tried not using a verbatim string instead like this:

var s = "     0     1\r\n    0     0"

and the tests then pass.

Does anyone have any idea what could be happening here?

4

There are 4 best solutions below

3
On BEST ANSWER

If you want to use the string in a unit test it is best to ensure the content is always the same. I suggest to declare it like this:

var s = $"     0     1{Enviroment.NewLine}0     0";
2
On

You can use string interpolation together with verbatim to add control characters.

var s = @$"     0     1{'\r'}
0     0"
0
On

Please check this answer - basically it is caused by code editor end of line settings. We faced the same issue in unit tests.

0
On

The answer is this: Git (most probably) swapped the line endings in the file to just LF. Depending on file line endings in unit tests is not a good idea so I have changed the code to specify the newlines explicitly in all cases, thus:

var s = "     0     1\r\n    0     0"