Here’re two extension methods for use
public static Type FindInterfaceWith(this Type type1, Type type2) {
// returns most suitable common implemented interface
}
public static Type FindBaseClassWith(this Type type1, Type type2) {
// returns most derivative of common base class
}
FindInterfaceWithreturnsnullif they don’t have common implemented interface.FindBaseClassWithreturnsSystem.Objectif they have no more derivative common base class.FindBaseClassWithreturnsnullif one of parameters was an interface.- Both they return
nullif any of parameter wasnull.
And the signature of method in finally solution would be like:
public static Type FindAssignableWith(this Type type1, Type type2) {
// what should be here?
}
Reflection and Linq are restricted to use, except there are no other way.
Are there good ways to find the best fit of common type between type1 and type2?
Or are there something better to achieve this?
update:
By my personal understanding, because of the ability to implement multiple interfaces with a class, the FindInterfaceWith could possibly need to call FindBaseClassWith internally; otherwise the best choice of type would be undecidable.
If this supposition was correct, then the FindInterfaceWith becomes a redundant method; because of the only difference between FindInterfaceWith and FindAssignableWith is:
FindInterfaceWith returns null if there was a best choice of class; while FindAssignableWith returns the exact class directly.
Otherwise, they both return a best choice of interface.
This is about saying the original assumption was irrational. That is, FindInterfaceWith cannot be implemented if FindAssignableWith is not.
Here is my implementation:
FindAssignableWith,FindBaseClassWithandFindInterfaceWithimplementationsRemark regarding
FindInterfaceWithimplementationAny interfaces that implements either
IEnumerableorIEnumerable<T>will be selected before others, what I considered not to be correctOpen ended question of
FindInterfaceWithc# allow multiple interfaces to be implemented in one class, in this case first one of interfaces will be returned by
FindInterfaceWith, because there is no way how to know which of interfacesIAorIBare preferable in general in following sampleInterfaces and classes hierarchy
Test cases
And set of test cases using
NUnitassertions:FindBaseClassWithassertions exampleFindInterfaceWithassertions exampleFinAssignableWithassertions exampleDiscussion at CodeReview
Review of this answer at
codereview.stackexchange.comps:
Full sources available [here]