Home Ask Login Register

Developers Planet

Your answer is one click away!

Backwards_Dave February 2016

String.IndexOf(Char) vs String.IndexOf(Char, StringComparison)

Resharper recommended me to use:

int notesFirstSpaceIndex = notes.IndexOf(" ", StringComparison.Ordinal);

instead of:

int notesFirstSpaceIndex = notes.IndexOf(" ");

According to https://msdn.microsoft.com/en-us/library/kwb0bwyd(v=vs.110).aspx String.IndexOf(char) uses Ordinal anyway: "This method performs an ordinal (culture-insensitive) search".

What benefit would I gain from using the recommended approach if they both use StringComparison.Ordinal?


Yacoub Massad February 2016

When you call:

int notesFirstSpaceIndex = notes.IndexOf(" ");

You are passing a string " ".

This means that you are using the following overload of the method:

public int IndexOf(string value)

Quoting from the reference above:

This method performs a word (case-sensitive and culture-sensitive) search using the current culture.

Which means that it is equivalent to:

int notesFirstSpaceIndex = notes.IndexOf(" ", StringComparison.CurrentCulture);

Regarding the difference (between calling an overload that takes no parameter, and the corresponding overload passing the default value as the paremeter), the difference is almost nothing. If you look at the source code of the first overload of the method, it actually calls the other overload of the method passing the default value as the parameter value.

Post Status

Asked in February 2016
Viewed 2,817 times
Voted 14
Answered 1 times


Leave an answer

Quote of the day: live life