Tim Rutter
Tim Rutter

Reputation: 4679

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?

Upvotes: 2

Views: 888

Answers (4)

Pavel Cermak
Pavel Cermak

Reputation: 1295

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

Upvotes: 0

Bartosz Wójtowicz
Bartosz Wójtowicz

Reputation: 1401

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

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

Upvotes: 1

Tim Rutter
Tim Rutter

Reputation: 4679

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"

Upvotes: 2

Stefan
Stefan

Reputation: 652

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

Upvotes: 1

Related Questions