views:

91

answers:

2

Let's assume type MyType implements interface IMyInterface. How to find type declaring an interface ? For example,

class UnitTest 
{
  MyTypeBase : IMyInterface  { }
  MyType : MyTypeBase  { }

  void Test() {
    Type declaration = FindDeclaration(typeof(MyType), typeof(IMyInterface));
    Assert.AreEqual(typeof(MyTypeBase), declaration) 
  }
A: 

You would walk up Type.BaseType until you've got to the level you want?

Noon Silk
Well, thanks, this works for classes. But this does not work well for interfaces.
Alex Ilyin
I guess, there should be some trick :)
Alex Ilyin
What? Didn't you want to find the class, not the interface?
Noon Silk
I mean, MyType and MyTypeBase are classes just for sample. if MyType is interface and MyTypeBase is interface it makes difference.
Alex Ilyin
But at runtime you have an object. You call .GetType() on that, and you walk up .BaseType until you find what you want. Have you written the code? Maybe I'm mistaken.
Noon Silk
I can't use .BaseType for interface type. As I know, for interfaces I can use .GetInterfaces() but is not very elegant.
Alex Ilyin
+1  A: 

You need to use the GetInterface or GetInterfaces methods of the Type.

For example you could do this:

Type declaration = typeof(MyType).GetInterface("IMyInterface");
Assert.IsNotNull(declaration)

Or you could call GetInterfaces and loop through the results until you find IMyInterface.

Sources:

Type.GetInterface(string)

Type.GetInterfaces()

Adam Hughes
Yes, unfortunately, It turns out that iterating through interfaces calling GetInterfaces is the only solution.
Alex Ilyin