How to create the object of the class present in the dynamically loaded Assembly(DLL)?

Hi All,

I have DLL (Assembly) say the name is test.dll . This dll has one class say Math, Math contains two functions Add() and Mul().

I am loading test.dll at runtime Assembly *** = Assembly.LoadFrom(xml[0]);

I am getting all the types in that DLL using Type [] types = ***.GetTypes();

With this piece of code I am able to execute the function inside the code,

foreach (Type typ in types)

{ object obj = Activator.CreateInstance(typ);

MethodInfo mi = typ.GetMethod(“add”);

try

{

mi.Invoke(obj,new object[]{ 10,20});

}

catch(Exception ex)

{ string msg = ex.Message; }

}

Now all I want if create the object of the class Math. My intension is to add the member function of the class Math to an event delegates.

For that I am trying to create the object of the class math by object obj = Activator.CreateInstance(typ);

If I try this Math obj = Activator.CreateInstance(typ); it is showing an error saying that Math is not a valid type or namespace (Obviosly since complier don’t know what Math is)

I want to create the object of the class Math present in the DLL test.dll and access the member functions of the class and create register a it to a event delegate and call the function by raising an event.

It is possible I suppose, please let me know how can I achieve it.




Answer this question

How to create the object of the class present in the dynamically loaded Assembly(DLL)?

  • BJBear

    The typical way would be to make Math implement an interface which your calling code has a reference to. See http://www.pobox.com/~skeet/csharp/plugin.html for sample code and caveats.

    However, if you're using reflection anyway, you don't need to know the interface - just use Delegate.CreateDelegate(Type, object, string).

    (Note that one of the deficiencies in reflection, at least in 1.1, is that there isn't a Delegate.CreateDelegate(Type, MethodInfo, object), which would make it easier to use this for overloaded methods.)

    Jon



  • Uriparan

    Hi Jon Skeet,

    Thank you for your reply. It was very very helpful for me. I would like to have your personal id if you don't mind. I am a person who started my career with java. I am very much impressed by C# so decided to buildup career further in C#. Please guide me through.

    With Regards,

    Anand.



  • How to create the object of the class present in the dynamically loaded Assembly(DLL)?