Alex Ilyin
Alex Ilyin

Reputation: 1304

Get .NET type declaring an interface

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) 
  }

Upvotes: 2

Views: 743

Answers (2)

Adam Hughes
Adam Hughes

Reputation: 3812

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()

Upvotes: 1

Noon Silk
Noon Silk

Reputation: 55082

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

Upvotes: 0

Related Questions