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?
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.
Edit: This answer is wrong! Please see comments.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With