How To Tell If A Type Supports And Interface

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I am using reflection and trying to determine if an assembly contains a type
that has a particular interface. So my code looks like this:

Assembly assembly = Assembly.LoadFile(fileName);
foreach (Module module in assembly.GetModules())
{
foreach (Type type in module.GetTypes())
{
try
{
object instance = Activator.CreateInstance(type);
if (instance is IMyInterface)
{
.. Do Something
}
}
catch
{
}
}
}

However, I would prefer not to have call CreateInstance then check the
object returned to see if it supports the interface. Is there anyway to
check the "Type" to see if it supports the interface without having to call
CreateInstance?

-Wayne
 
However, I would prefer not to have call CreateInstance then check the
object returned to see if it supports the interface. Is there anyway to
check the "Type" to see if it supports the interface without having to call
CreateInstance?

See Type.IsAssignableFrom.
 
Jon,

Thanks got it. Code change for those following along:

Assembly assembly = Assembly.LoadFile(fileName);
foreach (Module module in assembly.GetModules())
{
foreach (Type type in module.GetTypes())
{
if (typeof(IMyInterface).IsAssignableFrom(type))
{
.. Do Something
}
}
}
 
That is a cool little check -- however in my case I know if the Interface is
support it is the class I want.

-Wayne
 
Jeff Louie said:
John.... Is there also a need to check for && ! t.IsAbstract?

Yes, potentially - it depends on what you're doing with the results, I
guess. A lot of the time you will indeed want to check for it not being
abstract, and potentially it having a public parameterless constructor.
 
Back
Top