0

I wonder for what reason we need to use Comparer.Default as calling .Sort() by default will call CompareTo() function? e.g.,

List<string> list = new List<string>() { "Apple", "Orange", "Banana" };
list.Sort();
list.Sort(Comparer<String>.Default);

Isn't list.Sort() totally equivalent to list.Sort(Comparer<String>.Default)? so what's the reason behind having Comparer<T>.Default?

Abdulkarim Kanaan
  • 1,703
  • 4
  • 20
  • 32
  • Does `list.Sort()` automatically default to using `Comparer<>.Default` behind the scenes? – Carcigenicate Jul 09 '17 at 04:48
  • First, `List.Sort()` is not the only time one needs an `IComparer` implementation. Second, there are lots of different opinions you might get in answer to your question. That said, why do you think it not useful to have a single object that can be used, rather than having to create a new one each time you want to provide an `IComparer`? – Peter Duniho Jul 09 '17 at 04:49
  • one example I can think of is comparing generic type https://stackoverflow.com/questions/488250/c-sharp-compare-two-generic-values – Slai Jul 09 '17 at 05:18
  • 1
    It exists because it is doing a very untrivial job. The troublemaker is `IComparable`, an interface that a type *may* implement to customize the comparison. But methods like Sort require a `Comparer`. Turning a generic interface into a class object is something that you cannot do in C#, the Default property implementation uses a backdoor provided by the CLR named CreateInstanceForAnotherGenericParameter(). Note how the MSDN docs for IComparable recommend that you create your own Comparer instead. – Hans Passant Jul 09 '17 at 10:54

0 Answers0