简体   繁体   中英

C# Verbatim String Line Breaks: CRLF, CR, or LF?

I ran into an interesting problem today where my tests were failing consistently on the build machine when they worked just fine on my machine even using the same configuration. When I looked at the differences output by Assert.AreEqual in the failure dump, I couldn't see anything different. After a bunch of investigation, I came to find out that the verbatim string in the test case source code (which spanned multiple lines) was using CRLF on my machine, but using LF on the build machine, causing comparisons of that string with a generated string to fail. The culprit turned out to be inconsistent Git settings on the two systems, with the build system automatically converting CRLF sequences to just LF.

Does the C# specification say anything about how line breaks in verbatim strings should be interpreted (perhaps using Environment.Newline, or at least something consistent)? This seems like a problem that could bite lots of people in very hard to diagnose and hard to fix ways, especially with .NET Standard. For example, if you have a .NET Standard project, and have team members on both Linux and Windows, this is likely to bite either the Linux team members or the Windows team members.

The spec addresses this by not addressing it:

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/lexical-structure

In a verbatim string literal, the characters between the delimiters are interpreted verbatim, the only exception being a quote_escape_sequence .

Since no exception is made for line endings, you get whatever line endings were used in the source file. As you found out.

This solution based on the Git Help documentation may help ensure consistency regardless of each Git instance's setting.

As per the documentation in https://help.github.com/articles/dealing-with-line-endings/

Optionally, you can configure the way Git manages line endings on a per-repository basis by configuring a special .gitattributes file. This file is committed into the repository and overrides an individual's core.autocrlf setting, ensuring consistent behavior for all users, regardless of their Git settings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM