C# – can’t pass default comparer as IComparer


I'm trying to call a "Sort" method that expects a parameter of type IComparer<object>, using the code:


It builds but at run time I get an InvalidCastException with the message:

Unable to cast object of type
to type 'System.Collections.Generic.IComparer`1[System.Object]'.

Now what?

Best Solution

If all you want is the default comparison, this will work:


Comparer.Default uses your objects' inherent comparison semantics (i.e., IComparable.CompareTo).