Introduction to Reflection API

MethodInfo

The MethodInfo class discovers the attributes of a method and provides access to method metadata.

The GetMethods method on the Type class returns all the public instance methods on a type by default. Here, we get an array of MethodInfo instances of all the public MyClass class methods.

System.Reflection.MethodInfo[] methodInfos = myClassType.GetMethods();
//or
System.Reflection.MethodInfo[] methodInfos = myClassType.GetTypeInfo().DeclaredMethods;

Aslo we can get single MethodInfo by method name

Type type = typeof(MyClass);

MethodInfo info = type.GetMethod("SomeMethod");

 

An instance method can be called by its name. With the MethodInfo type, we call the Invoke method. We must provide an instance expression. 

var type = typeof(MyClass);

var instance  = new MyClass();

var methodInfo = type.GetMethod("SomeMethod");
    
methodInfo.Invoke(instance, null); // second parameter is array of parameters of the invoked method

Other properties and methods you can check on MSDN

Example

Get all methods in class Program and invoke them

using System; using System.Reflection; ...

 

Page 9 of 11