Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a specified type is a match for a generic type?

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.

like image 936
Alex Hope O'Connor Avatar asked Jan 23 '26 10:01

Alex Hope O'Connor


1 Answers

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)));
}
like image 64
Peter Avatar answered Jan 24 '26 22:01

Peter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!