Question

Using reflection in .Net, what is the differnce between:

   if (foo.IsAssignableFrom(typeof(IBar)))

And

   if (foo.GetInterface(typeof(IBar).FullName) != null)

Which is more appropriate, why?

When could one or the other fail?

Was it helpful?

Solution

If you just want to see if a type implements a given interface, either is fine, though GetInterface() is probably faster since IsAssignableFrom() does more internal checks than GetInterface(). It'll probably even faster to check the results of Type.GetInterfaces() which returns the same internal list that both of the other methods use anyway.

OTHER TIPS

There is a difference in how internal classes are handled. Take the following class:

public interface IFoo
{
}    

internal class Foo: IFoo
{
}

This will give you a list of one item:

var types = typeof(IFoo).Assembly.GetTypes()
            .Where(x => x.GetInterface(typeof(IFoo).FullName) != null)
            .ToList();

Whereas this will give you an empty list:

var types = typeof(IFoo).Assembly.GetTypes()
            .Where(x => x.IsAssignableFrom(typeof(IFoo))
            .ToList();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top