I'm writing a comparer library of sorts that can accept any type and compares it. Now I'm creating an ordered comparison which could use Comparer<T>.Default.Compare
since it does exactly what I want. How would I go about constructing it without knowing the type T
at compile-time?
Something like
public static int CompareOrdered<T>(T lhs, T rhs) {
return Comparer<T>.Default.Compare(lhs, rhs);
}
will not work since T
will most often be of type object
and I want the most accurate type filled in for T
.
What I have now is the following where we assume lhs
has the correct comparison type.
public static int CompareOrdered(object lhs, object rhs) {
var type = lhs.GetType();
var comparerType = typeof(Comparer<>).MakeGenericType(type);
var comparer = comparerType
.GetProperty("Default", BindingFlags.Public | BindingFlags.Static)
.GetValue(null);
var func = comparerType
.GetMethod("Compare", BindingFlags.Public | BindingFlags.Instance);
return (int)func.Invoke(comparer, new[] { lhs, rhs });
}
Which is incredibly ugly. I searched for a general Comparer
type where T
is not needed, but that does not exist. That would allow for ((Comparer)comparer).Default.Compare(lhs,rhs)
which is already a lot better, cleaner and less error-prone way to do this.
So, is there a more proper way to do this?