Reputation: 9724
Lets say I have the following dictionary:
protected Dictionary<Type, Type> MatchingTypes = new Dictionary<Type, Type>()
{
{ typeof(ObservableList<>), typeof(XmlDataModel.XmlObjectCollection<>) }
};
And I have a method with a signature that resembles this:
public CheckTypesMatch(Type one, Type two)
{
return MatchingTypes.Any(kv => ((kv.Key == one && kv.Value == two) || (kv.Value == one && kv.Key == two)));
}
This will work fine for non-generic types, however for the generic types above this method will not return true.
Can someone outline how I can modify my code to make this method work for generic types?
Thanks, Alex.
Upvotes: 3
Views: 979
Reputation: 3956
CheckTypesMatch(typeof(ObservableList<>), typeof(XmlDataModel.XmlObjectCollection<>))
returns true for me.
If you want it to also return true for e.g. typeof(ObervableList<int>)
you can rewrite it like the following:
public bool CheckTypesMatch(Type one, Type two)
{
var one2 = one.IsGenericType ? one.GetGenericTypeDefinition() : one;
var two2 = two.IsGenericType ? two.GetGenericTypeDefinition() : two;
return MatchingTypes.Any(
kv => ((kv.Key == one2 && kv.Value == two2)
|| (kv.Value == one2 && kv.Key == two2)));
}
Upvotes: 4