Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the name(s) of interface methods strong typed

Tags:

c#

c#-4.0

i have an interface like this example:

Interface IRequest{

  List<profile> GetProfiles();
  void SetProfile (Profile p);
}

Now, in some logging component, i don't have access to the object implementing the interface, but i want to use the names of the methods in the interface. i can of course type them as a string (copy the method name in a string), but i want to use them strong typed so i don't have to keep the method names and string in sync.

In pseudo code, i would do this:

string s= IRequest.GetProfiles.ToString()

Is this in a way possible?

EDIT:

Maybe i should call it: use the interface like it's an Enum string s= IRequest.GetProfiles.ToString()

like image 805
Michel Avatar asked Feb 23 '12 11:02

Michel


People also ask

What are interface methods in C#?

Interface methods do not have a body - the body is provided by the "implement" class. On implementation of an interface, you must override all of its methods. Interfaces can contain properties and methods, but not fields/variables. Interface members are by default abstract and public.

WHAT IS interface in C# with example?

Interface in C# is a blueprint of a class. It is like abstract class because all the methods which are declared inside the interface are abstract methods. It cannot have method body and cannot be instantiated. It is used to achieve multiple inheritance which can't be achieved by class.

Why interfaces are used in C#?

By using interfaces, you can, for example, include behavior from multiple sources in a class. That capability is important in C# because the language doesn't support multiple inheritance of classes.

CAN interface have variables in C#?

In C#, you are allowed to create a reference variable of an interface type or in other words, you are allowed to create an interface reference variable. Such kind of variable can refer to any object that implements its interface.


1 Answers

You can achieve this in two ways:

//If you CAN access the instance
var instance = new YourClass(); //instance of class implementing the interface
var interfaces = instance.GetType().GetInterfaces();

//Otherwise get the type of the class
var classType = typeof(YourClass); //Get Type of the class implementing the interface
var interfaces = classType.GetInterfaces()

And then:

foreach(Type iface in interfaces)
{
    var methods = iface.GetMethods();

    foreach(MethodInfo method in methods)
    {        
        var methodName = method.Name;
    }
}
like image 128
Abbas Avatar answered Nov 07 '22 13:11

Abbas