Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Why does this code have different results on different OS #5522

Closed
crystal-lz opened this issue Nov 5, 2020 · 2 comments
Closed

Why does this code have different results on different OS #5522

crystal-lz opened this issue Nov 5, 2020 · 2 comments
Labels

Comments

@crystal-lz
Copy link

string strText = "1123\r\ntest\tabc";
Console.WriteLine($"TEXT[{strText}]\r\n");
Console.WriteLine($"IndexOf [\\r] {strText.IndexOf("\r")}");
Console.WriteLine($"IndexOf [\\n] {strText.IndexOf("\n")}");
Console.WriteLine($"IndexOf [\\t] {strText.IndexOf("\t")}");

//==output=====[mac or ubuntu]=======

TEXT:[1123
test    abc]

IndexOf [\r] 4
IndexOf [\n] -1
IndexOf [\t] 10
//---------------------------------------
-1  ?????????? 
@carlossanlop
Copy link
Member

@GrabYourPitchforks I think you may have some context on this question. Can you please help?

@GrabYourPitchforks
Copy link
Member

GrabYourPitchforks commented Nov 9, 2020

Related to dotnet/runtime#43736.
(Edit: this isn't a dupe, but the issue has the same explanation. I've summarized it below.)

In a nutshell, the overload of string.IndexOf that's being called is performing a culture-sensitive check, when an ordinal check is intended.

There are two suggested workarounds:

  1. If you're searching for a single char (e.g., '\n'), change the code from strText.IndexOf("\n") to strText.IndexOf('\n') instead. Searching for single chars will be ordinal.
  2. If you're searching for a literal substring, change the code from strText.IndexOf("text") to strText.IndexOf("text", StringComparison.Ordinal) instead.

The code analyzer rules CA1307 and CA1309 can assist with this. See dotnet/docs#21249, section "Option 1: Enable code analyzers to help detect possibly-buggy call sites" for more information.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants