Search code examples
c#.netdllclass-library

Loading DLL in external program?


I have a C# ClassLibrary that contains a function to sum two numbers:

namespace ClassLibrary1
{
    public class Calculator
    {
        public int Calc(int i, int b) {
            return i + b;
        }
    }
}

I want to load this dll from other C# application externally. How can I do this?


Solution

  • Do you mean you want to load it dynamically, by file name? Then yes, you can use the Assembly.LoadFile method as follows:

    // Load the assembly
    Assembly a = Assembly.LoadFile(@"C:\Path\To\Your\DLL.dll");
    
    // Load the type and create an instance
    Type t = a.GetType("ClassLibrary1.Calculator");
    object instance = a.CreateInstance("ClassLibrary1.Calculator");
    
    // Call the method
    MethodInfo m = t.GetMethod("Calc");
    m.Invoke(instance, new object[] {}); // Get the result here
    

    (Translated example from here, but I wrote it so don't worry!)