views:

1521

answers:

3

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

   if (foo.IsAssignableFrom(IBar))

And

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

Which is more appropriate, why?

When could one or the other fail?

+1  A: 

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.

Mark Cidade
A: 

If memory serves, IsAssignableFrom will include any implicit/explicit operator overloads, whereas GetInterface will not (it is strictly type definition).

Richard Szalay
A: 

@Richard Szalay

If memory serves, IsAssignableFrom will include any implicit/explicit operator overloads, whereas GetInterface will not (it is strictly type definition).

Implicit conversions are not included in IsAssignableFrom. Perhaps a bit unintuitive, but remember that in a conversion, you do not assign the instance to the variable. You create a new instance of another type and assign that to the variable - even though the syntax resembles an assignment.

Rasmus Faber