views:

309

answers:

2

How can I reflect on the interfaces implemented by a given type (of class or interface) in .NET?

As the type being reflected on will be generic (both in the implementation sense as well as the semantic sense), it would preferable to do this without having to hardcode an Assembly name, though I realise that I can get this name from the Type class of any given type.

+1  A: 

Call Type.GetInterfaces().

itowlson
Now that would be too simple ;) Thanks.
johnc
+1  A: 

Type.GetInterfaces() only gets you declared interfaces (MSDN should have documentation that explains this). To get inherited interfaces you must do the work yourself. Something similar to:


using System;
using System.Linq;

public static IEnumerable<Type> GetAllInterfacesForType(this Type type)
{
   foreach (var interfaceType in type.GetInterfaces())
   {
       yield return interfaceType;
       foreach (var t in interfaceType.GetAllInterfacesForType())
           yield return t;
   }
}


public static IEnumerable<Type> GetUniqueInterfacesForType(this Type type)
{ return type.GetAllInterfaces().Distinct(); }


I wrote this off the cuff so sorry if it doesn't compile straight-outta-da-box.

Michael Smith
I don't think this is correct. From MSDN return for GetInterfaces() is:Type: array<System..::.Type>[]()[]An array of Type objects representing all the interfaces implemented or inherited by the current Type.
tylerl
MSDN is correct. GetInterfaces returns interfaces inherited from base types as well as interfaces declared on the type at hand.
itowlson
Again, and you're not going to believe me until you try it yourself, but that still means that it's only those DECLARED on the class. Read the COMMENTS to that article on MSDN.
Michael Smith
I did try it before posting my comment, because I wanted to be sure before weighing in. I tried it again just now in case I'd misread the results of my first test. What I'm seeing (on .NET 3.5 SP1) is that interfaces declared on base classes *are* included in the results of GetInterfaces, just as MSDN says. Unfortunately there's not enough room in the comment to post the test code -- sorry!
itowlson
I'm sorry, I must have it confused with the <code>FindInterfaces</code> call or something.
Michael Smith