Skip to content

Instantly share code, notes, and snippets.

@redknitin
Created November 16, 2015 09:11
Show Gist options
  • Select an option

  • Save redknitin/7e593e507d8d39aefb97 to your computer and use it in GitHub Desktop.

Select an option

Save redknitin/7e593e507d8d39aefb97 to your computer and use it in GitHub Desktop.
Dynamically load DLL in .NET
//This is in LibFunctions.dll
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LibFunctions
{
public class InstanceThing
{
public int Sum(int a, int b) { return a + b; }
}
}
//This is in LoadWithReflection.exe
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
namespace LoadWithReflection
{
class Program
{
static void Main(string[] args)
{
Assembly Lib = Assembly.LoadFrom("LibFunctions.dll");
Type instanceThingType;
Type staticThingType;
Object instanceThingObject;
if (null != (instanceThingType = Lib.GetType("LibFunctions.InstanceThing")))
{
instanceThingObject = Activator.CreateInstance(instanceThingType);
MethodInfo mi = instanceThingType.GetMethod("Sum");
object resultI = mi.Invoke(instanceThingObject, new object[] { 1, 2 });
Console.WriteLine(resultI.ToString());
}
else { Console.WriteLine("Type not found"); }
if (null != (staticThingType = Lib.GetType("LibFunctions.StaticThing")))
{
MethodInfo ms = staticThingType.GetMethod("Sum");
object resultS = ms.Invoke(null, new object[] { 3, 4 });
Console.WriteLine(resultS.ToString());
}
else { Console.WriteLine("Type not found"); }
Console.WriteLine("Finished");
Console.Read();
}
}
}
//This is in LibFunctions.dll
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LibFunctions
{
public static class StaticThing
{
public static int Sum(int a, int b) { return a + b; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment