I'm trying to call a "Sort" method that expects a parameter of type IComparer<object>
, using the code:
collection.Sort((IComparer<object>)Comparer<DateTime>.Default)
It builds but at run time I get an InvalidCastException with the message:
Unable to cast object of type
'System.Collections.Generic.GenericComparer`1[System.DateTime]'
to type 'System.Collections.Generic.IComparer`1[System.Object]'.
Now what?
If all you want is the default comparison, this will work:
collection.Sort(Comparer<object>.Default)
Comparer.Default uses your objects' inherent comparison semantics (i.e., IComparable.CompareTo).