Get a method and invoke it

suggest change

Get Instance method and invoke it

using System;
                
public class Program
{
    public static void Main()
    {
        var theString = "hello";
        var method = theString
                     .GetType()
                     .GetMethod("Substring",
                                new[] {typeof(int), typeof(int)}); //The types of the method arguments
         var result = method.Invoke(theString, new object[] {0, 4});
         Console.WriteLine(result);
    }
}

Output:

hell

View Demo

Get Static method and invoke it

On the other hand, if the method is static, you do not need an instance to call it.

var method = typeof(Math).GetMethod("Exp");
var result = method.Invoke(null, new object[] {2});//Pass null as the first argument (no need for an instance)
Console.WriteLine(result); //You'll get e^2

Output:

7.38905609893065

View Demo

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Reflection:
* Get a method and invoke it

Table Of Contents
17 Regex
19 Arrays
21 Enum
22 Tuples
24 GUID
27 Looping
36 Casting
46 Methods
61 Reflection
88 Events
92 Structs
104 Indexer
106 Stream
107 Timers
109 Threading
127 Caching
135 Pointers
147 C# Script