0

Under the "Common Practices and Code Improvements" rubric, Resharper says about this line:

If dt(0)("ThemeWidth").ToString.IndexOf("%") > "0" Then
    headerPanel.Width = Unit.Percentage(dt(0)("ThemeWidth").ToString.Replace("%", ""))

"String.IndexOf(string) is culture-specific" and encourages me to change it to this:

If dt(0)("ThemeWidth").ToString.IndexOf("%", StringComparison.Ordinal) > "0" Then
    headerPanel.Width = Unit.Percentage(dt(0)("ThemeWidth").ToString.Replace("%", ""))

Why? What does adding "StringComparison.Ordinal" do for me that improves this code?

B. Clay Shannon-B. Crow Raven
  • 8,547
  • 144
  • 472
  • 862
  • The robot is likely just parroting stuff back from MSDN such as `Use StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase for comparisons as your safe default for culture-agnostic string matching.` See [Best Practices for Using Strings in the .NET Framework](https://msdn.microsoft.com/en-us/library/dd465121(v=vs.110).aspx)... or dont take orders from robots – Ňɏssa Pøngjǣrdenlarp Dec 01 '16 at 21:41
  • 3
    Was it Mark Twain who once said *Those who cannot remember the past are condemned to repeat it.*? See [Could string comparisons really differ based on culture when the string is guaranteed not to change](http://stackoverflow.com/q/10941375/1070452) – Ňɏssa Pøngjǣrdenlarp Dec 01 '16 at 21:47
  • No, that was Santayana. – B. Clay Shannon-B. Crow Raven Dec 01 '16 at 22:36

1 Answers1

2

Consider the following example:

Dim longText As String = "01234ss789ß"
Dim shortText As String = "ß"

Dim index1 As Integer = longText.IndexOf(shortText)
Dim index2 As Integer = longText.IndexOf(shortText, StringComparison.Ordinal)

Naively, you would expect IndexOf to return 10, because the "ß" sign only occurs at the very end of the string.

But in some cultures, the ß sign is seen as an alias for two ss and so the IndexOf without additional parameter will return 5 on some computers and 10 on other computers.

When using the parameter StringComparison.Ordinal, all cultural differences will be ignored and it will return 10 predictably on all computers.

NineBerry
  • 26,306
  • 3
  • 62
  • 93