Essential C# Reflection  Suggest an edit

Get a method and invoke it

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


Table Of Contents
22 Enum
25 GUID
62 Reflection
107 Stream
108 Timers
  ↑ ↓ to navigate     ↵ to select     Esc to close