Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between, IsAssignableFrom and GetInterface?

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?

like image 869
Nescio Avatar asked Sep 19 '08 04:09

Nescio


2 Answers

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.

like image 143
Mark Cidade Avatar answered Nov 13 '22 07:11

Mark Cidade


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();
like image 1
Holf Avatar answered Nov 13 '22 08:11

Holf