'Verbatim string is missing carriage return

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?



Solution 1:[1]

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

Solution 2:[2]

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"

Solution 3:[3]

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

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

Solution 4:[4]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Stefan
Solution 2 Tim Rutter
Solution 3 Bartosz Wójtowicz
Solution 4 Pavel Cermak