Skip to main content

C# example of loading a remote/satellite assembly from the specified path, and Dynamically invoking a static method using reflection.

using System;
using System.Reflection;

internal class Program
{
    public class Person
    {
        public string Name { get; set; }
    }

    private static void Main(string[] args)
    {
        var assemblyPath = @"/Users/jon/.nuget/packages/newtonsoft.json/11.0.2/lib/netstandard2.0/Newtonsoft.Json.dll";
        Assembly assembly = Assembly.LoadFrom(assemblyPath);
        Type type = assembly.GetType("Newtonsoft.Json.JsonConvert", true);
        var method = type.GetMethod("SerializeObject", new [] { typeof(object) });

        var person = new Person { Name = "Jon Doe." };

        var methodParams = new object[] { person };
        var methodResult = method.Invoke(null, methodParams);

        Console.WriteLine(methodResult.ToString());
    }
}

//
// Related:
//  - [Dynamically invoking a static method with Reflection in .NET C#](https://dotnetcodr.com/2014/10/15/dynamically-invoking-a-static-method-with-reflection-in-net-c/)
//  - [C# reflection - load assembly and invoke a method if it exists](https://stackoverflow.com/a/24548654)