I have the following utility program that determines if a type of a specific type occurs:
private static bool DerivesFrom(Type rType, Type rDerivedType)
{
while ((rType != null) && ((rType != rDerivedType)))
rType = rType.BaseType;
return (rType == rDerivedType);
}
(actually I don't know if there is a more convenient way to check the output ...)
The problem is that I want to determine if a type arises from a generic type, but without specifying general arguments.
For example, I can write:
DerivesFrom(typeof(ClassA), typeof(MyGenericClass<ClassB>))
but i need the following
DerivesFrom(typeof(ClassA), typeof(MyGenericClass))
How can i achieve this?
Based on the example of Darin Miritrova, this is an example 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);
}
private static bool DerivesFrom(Type rType, Type rDerivedType)
{
return rType.IsSubclassOf(rDerivedType);
}
}
}
source
share