marcelo-ferraz
marcelo-ferraz

Reputation: 3257

Find the generic type

Throughout reflection is there a way of achieving this?
get IDictionary<,> from IDictionary<int,int>, per instance?

my intention is:

 typeof(UniqueKeyQuery<,>).IsAssignableFrom(query.GetType())

Whereas 'query' is of type UniqueKeyQuery<Sometype,int>.
I don`t want to compare names, as I want to UniqueKeyQuery to be extensible.

Upvotes: 2

Views: 60

Answers (2)

Daniel M&#246;ller
Daniel M&#246;ller

Reputation: 86650

You can try

typeof(UniqueKeyQuery<,>).IsAssignableFrom(query.GetType().GetGenericDefitition())

If it doesn't work, you can use this (a static extension method that should be in a static class)

public static bool IsOrInheritsGenericDefinition(this Type ThisType, Type GenericDefinition, out Type DefinitionWithTypedParameters)
    {
        DefinitionWithTypedParameters = ThisType;

        while (DefinitionWithTypedParameters != null)
        {
            if (DefinitionWithTypedParameters.IsGenericType)
            {
                if (DefinitionWithTypedParameters.GetGenericTypeDefinition() == GenericDefinition)
                    return true;
            }

            DefinitionWithTypedParameters = DefinitionWithTypedParameters.BaseType;
        }

        return false;
    }

Call that by:

Type QueryType;
query.GetType().IsOrInheritsGenericDefinition(typeof(UniqueKeyQuery<,>), out QueryType);

Upvotes: 1

Mark Brackett
Mark Brackett

Reputation: 85675

If you want the "open" generic type of (eg., query) GetGenericTypeDefinition would work:

 typeof(UniqueKeyQuery<,>).IsAssignableFrom(
     query.GetType().GetGenericTypeDefinition()
 )

Upvotes: 2

Related Questions