Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Find out if a class is derived from an interface or a base class?

Status
Not open for further replies.

huckfinn19

Programmer
May 16, 2003
90
CA
Hi,

I need to be able to find out if a class is derived from a particular interface.

I know that it is possible to find out if a class is derived from a base class with the System.Type class with the following code:
Code:
public class Class1 {}
public class Class2 : Class1 {}

if(typeof(Class2).IsSubclassOf(typeof(Class1)))
   ...

I need the same thing for interfaces. Does anything exist that does the same kind of job than IsSubclassOf for class inheritance but for interface inheritance?

If not, how could I find out if a class is derived from a particular interface?

Thanks!

Huck
 
According to what I'm seeing on MSDN IsSubclassOf should work for both object inheritance and interface implementation:
You can use this comparison with both interface implementation and object inheritance for a particular object instance as well:

Code:
public interface IClass {}
public class Class1 {}
public class Class2 : Class1 : IClass {}

void TestInstance(object obj) {
if (obj is IClass)
...

if (obj is Class1)
...
}
 
Hi!

Thanks for the answer. What about if I am dealing only with types and not instances?

The ultimate goal is a plugin manager in which class types will be registered. They will then be retrived by groups filtrered by their inheritance from a particular interface. This means that in the plugin manager, I deal only with types.

Currently, I am using the following code:
Code:
private bool IsDerivedFrom(Type oType, Type oBaseType){
   if(oBaseType.IsInterface){
      ArrayList aoInterfaces = new ArrayList();
      aoInterfaces.AddRange(oType.GetInterfaces());
      if(aoInterfaces.Contains(oBaseType)){
         return true;
      }
   }
   else if(oType.IsSubclassOf(oBaseType)){
      return true;
   }
   return false;
}

Do you know anything simpler? I don't like to have to create an arraylist every time the base type is an interface since it is almost always going to be the case...

Thanks again!

Huck
 
According to MSDN, this should be sufficient for both interfaces and inheritance:

Code:
private bool IsDerivedFrom(Type oType, Type oBaseType){
   return oType.IsSubclassOf(oBaseType)){
}

Is the problem you are running into have to do with multiple layers of inheritance?

Code:
interface IClass1 {}
interface IClass2 : IClass1 {}
interface IClass3 : IClass2 {}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top