I have a class (Foo
) which is required to compare T
type objects, however T
may not always implement IComparable and the constructor should be able to be used with a null comparer
param. To catch this on creation of Foo
I attempted the following:
public sealed class Foo<T>
{
private readonly IComparer<T> _comparer;
public Foo(IComparer<T> comparer)
{
_comparer = comparer ?? Comparer<T>.Default;
if (_comparer == null)
throw new NotSupportedException("A comparer was not passed for T and no default was found for T. ");
}
}
I assumed (incorrectly) that Comparer<T>.Default
would be null if the object did not implement IComparable<T>
but instead Default
will still return a valid Comparer
which throws an ArgumentsException
when compare is called and I haven't been able to find a solution through research on how to approach this situation.
How should I approach this situation?
EDIT: To clarify This class should be able to sort objects of type T using the given Comparer. But T might not always have IComparable but when a Comparer is provided then it should still be able to sort those objects constraining would break that requirement. However if the passed in Comparer is null then it should attempt to use Default
, If the object is IComparable all is well if not it should throw an NotSupportedException
.