Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find if a method is implementing specific interface

Tags:

c#

reflection

I have a MehtodBase of a method and I need to know if that method is an implementation of a specific interface. So if I have the following class:

class MyClass : IMyInterface
{
    public void SomeMethod();
}

Implementing the interface:

interface IMyInterface
{
    void SomeMethod();
}

I want to be able to discover at runtime (using reflection) if a certain method implements IMyInterface.

like image 969
Dror Helper Avatar asked Sep 11 '11 15:09

Dror Helper


People also ask

How do you know if a class implements an interface?

To declare a class that implements an interface, you include an implements clause in the class declaration. Your class can implement more than one interface, so the implements keyword is followed by a comma-separated list of the interfaces implemented by the class.

Which keyword validates whether a class implements an interface?

With the aim to make the code robust, i would like to check that the class implements the interface before instantiation / casting. I would like the the keyword 'instanceof' to verify a class implements an interface, as i understand it, it only verifies class type.

Can methods be implemented in an interface?

Like a class, an interface can have methods and variables, but the methods declared in an interface are by default abstract (only method signature, no body). Interfaces specify what a class must do and not how.


1 Answers

You can use GetInterfaceMap for this.

InterfaceMapping map = typeof(MyClass).GetInterfaceMap(typeof(IMyInterface));

foreach (var method in map.TargetMethods)
{
    Console.WriteLine(method.Name + " implements IMyInterface");
}
like image 63
TheCodeKing Avatar answered Oct 24 '22 15:10

TheCodeKing