Skip to content
Ed Ball edited this page Jan 4, 2019 · 2 revisions

Optional IComparer<string> arguments must always be specified

Many methods that operate on strings default to using the current culture, which is not always correct. If a method has an overload that takes an IComparer<string> parameter, that overload should be invoked with an explicit IComparer<string> specified, e.g. using a static property from StringComparer.

var widgets = ReadWidgets().OrderBy(x => x.Id).ToList(); // BAD
var widgets = ReadWidgets().OrderBy(x => x.Id, StringComparer.Ordinal).ToList(); // GOOD

This analyzer also reports an error when orderby is used on a string. Switch to method syntax to specify the comparer.

var widgets = (from w in ReadWidgets() where !w.IsHidden orderby w.Id select w).ToList(); // BAD
var widgets = (from w in ReadWidgets() where !w.IsHidden select w).OrderBy(x => x.Id, StringComparer.Ordinal).ToList(); // GOOD

Further Reading

See Also

  • FL0002 Optional StringComparison arguments must always be specified
Clone this wiki locally