Finding the Subclasses of a Type




Finding the Subclasses of a Type

Problem

You have a type and you need to find out whether it is subclassed anywhere in an assembly.

Solution

Use the Type.IsSubclassOf method to test all types within a given assembly, which determines whether each type is a subclass of the type specified in the argument to IsSubClassOf:

	public static Type[] GetSubClasses(string asmPath, Type baseClassType)
	{
	    Assembly asm = Assembly.LoadFrom(asmPath);
	    return (GetSubClasses(asm, baseClassType));
	}

	public static Type[] GetSubClasses(Assembly asm, Type baseClassType)
	{
	    List<Type> subClasses = new List<Type>();

	    foreach(Type type in asm.GetTypes())
	    {
	        if (type.IsSubclassOf(baseClassType))
	        {
	            subClasses.Add(type);
	        }
	    }

	    return (subClasses.ToArray());
	}

The GetSubClasses method accepts an assembly path string and a second string containing a fully qualified base class name. This method returns a Type[] of Types representing the subclasses of the type passed to the baseClass parameter.

Discussion

The IsSubclassOf method on the Type class allows you to determine whether the current type is a subclass of the type passed in to this method.

The following code shows how to use this method:

	public static void FindSubClassOfType()
	{
	    Assembly asm = Assembly.GetExecutingAssembly();
	    Type type = Type.GetType("CSharpRecipes.ReflectionUtils+BaseOverrides");
	    Type[] subClasses = GetSubClasses(asm,type);

	    // Write out the subclasses for this type.
	    if(subClasses.Length > 0)
	    {
	        Console.WriteLine("{0} is subclassed by:",type.FullName);
	        foreach(Type t in subClasses)
	        {
	            Console.WriteLine("\t{0}",t.FullName);
	        }
	    }
	}

First you get the assembly path from the current process, and then you set up use of CSharpRecipes.ReflectionUtils+BaseOverrides as the type to test for subclasses. You call GetSubClasses, and it returns a Type[] that you use to produce the following output:

	CSharpRecipes.ReflectionUtils+BaseOverrides is subclassed by:
	        CSharpRecipes.ReflectionUtils+DerivedOverrides

See Also

See the "Assembly Class" and "Type Class" topics in the MSDN documentation.