How To Tell If A Type Supports And Interface

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
 
J

Jon Skeet [C# MVP]

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.
 
G

Guest

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
}
}
}
 
G

Guest

That is a cool little check -- however in my case I know if the Interface is
support it is the class I want.

-Wayne
 
J

Jon Skeet [C# MVP]

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top