C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
With the MethodInfo type, we call the Invoke method. We must provide an instance expression. We demonstrate the MethodInfo type, as well as the Invoke method.
Example. 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 Program class methods.
And: We print their names, but also test for the Win method. If we find this method, we call Invoke on it.
Based on: .NET 4.5 C# program that calls Invoke on MethodInfo using System; using System.Reflection; class Program { public void Win() { Console.WriteLine("{You're a winner}"); } public void Lose() { } public void Draw() { } static void Main() { // Instance used for Invoke. [1] Program program = new Program(); // Get methods. MethodInfo[] methods = typeof(Program).GetMethods(); foreach (MethodInfo info in methods) { Console.WriteLine(info.Name); // Call Win method. if (info.Name == "Win") { info.Invoke(program, null); // [2] } } } } Output Win {You're a winner} Lose Draw ToString Equals GetHashCode GetType
The Program class is instantiated inside the Main method. This instance is then passed as the first argument to the Invoke method. This is not the most natural way to use an object-oriented system, but it gets the job done.
Discussion. One of the more interesting uses for reflection in the C# language is to create programs that produce their own documentation. This would be typically most useful for large or complex programs.
But: The sort of code shown here could definitely be used as part of a system that prints all public methods on types.
Summary. We saw an example of GetMethods(), as well as the Invoke method on an instance method. There are other ways to call methods by name. Please check out the separate article on the topic on this website.
GetMethod: Call Method by Name