B. Clay Shannon B. Clay Shannon - 1 month ago 14
Vb.net Question

Why does Resharper recommend adding "StringComparison.Ordinal" to String.IndexOf?

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?


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.