Luca
Luca

Reputation: 11961

Determine type derivation from generic type

I have the following utility routine which determine whether a type derives from a specific type:

private static bool DerivesFrom(Type rType, Type rDerivedType)
{
    while ((rType != null) && ((rType != rDerivedType)))
        rType = rType.BaseType;
    return (rType == rDerivedType);
}

(actually I don't know whether there is a more convenient way to test the derivation...)

The problem is I want to determine whether a type derives from a generic type, but without specify the generic arguments.

For example I can write:

DerivesFrom(typeof(ClassA), typeof(MyGenericClass<ClassB>))

but what I need is the following

DerivesFrom(typeof(ClassA), typeof(MyGenericClass))

How can I achieve it?


Based on the example of Darin Miritrov, this is a sample application:

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;

namespace ConsoleApplication1
{
    public class MyGenericClass<T> { }
    public class ClassB {}
    public class ClassA : MyGenericClass<ClassB> { }

    class Program
    {
        static void Main()
        {
            bool result = DerivesFrom(typeof(ClassA), typeof(MyGenericClass<>));
            Console.WriteLine(result); // prints **false**
        }

        private static bool DerivesFrom(Type rType, Type rDerivedType)
        {
            return rType.IsSubclassOf(rDerivedType);
        }
    }
}

Upvotes: 3

Views: 852

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

You could leave the generic parameter open:

DerivesFrom(typeof(ClassA), typeof(MyGenericClass<>));

should work. Example:

public class ClassA { }
public class MyGenericClass<T>: ClassA { }

class Program
{
    static void Main()
    {
        var result = DerivesFrom(typeof(MyGenericClass<>), typeof(ClassA));
        Console.WriteLine(result); // prints True
    }

    private static bool DerivesFrom(Type rType, Type rDerivedType)
    {
        return rType.IsSubclassOf(rDerivedType);
    }
}

Also notice the usage of IsSubClassOf method which should simplify your DerivesFrom method and kind of defeat its purpose. There's also the IsAssignableFrom method you may take a look at.

Upvotes: 5

Related Questions