1

I am not a C# developer expert. I need to load a specific C# DLL under condition to execute a function named Sum.

Here is the DLL code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace testdll
{
    public class Class1
    {
        public int Sum(int a, int b)
        {
            return a + b;
        }
    }
}

Can someone confirm that the DLL is correctly unloaded when I am out of the context of the condition?

if(condition)
{
    Assembly myassembly = Assembly.LoadFrom (dllPath);
    Type type = myassembly.GetType("testdll.Class1");

    object instance = Activator.CreateInstance(type);
    MethodInfo[] methods = type.GetMethods();

    object res = null;

    // Display information for all methods. 
    for (int i = 0; i < methods.Length; i++)
    {
        MethodInfo myMethodInfo = (MethodInfo)methods[i];
        if (myMethodInfo.Name == "Sum")
        {
            res = methods[i].Invoke(instance, new object[] { 3, 5});
            break;
        }
    }

    if(res != null)
        MessageBox.Show("OK");
    else
        MessageBox.Show("KO");
}
Francois Nel
  • 1,662
  • 2
  • 19
  • 29
sdespont
  • 13,915
  • 9
  • 56
  • 97
  • See [How to unload the .dll using c#?](http://stackoverflow.com/questions/1371877/how-to-unload-the-dll-using-c). You can't (easily). – CodeCaster Jan 10 '14 at 12:45

1 Answers1

1

see Unloading the Assembly loaded with Assembly.LoadFrom()

answer from here:

"Unfortunately you can not unload an assembly once it is loaded. But you can unload an AppDomain. What you can do is to create a new AppDomain (AppDomain.CreateDomain(...) ), load the assembly into this appdomain to work with it, and then unload the AppDomain when needed. When unloading the AppDomain, all assemblies that have been loaded will be unloaded. (See reference)"

Community
  • 1
  • 1
Alexander Egorov
  • 593
  • 10
  • 14