Dynamica invocation of a Method in DLL using C#

Hi,
Here we are going to look how to invoke a method in a DLL dynamically using C#. First You need to create a class library with the following code.


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

namespace MyClassLibrary
{
public class ReflectionClass
{
public void GetName()
{
Console.WriteLine("Brainstorming Guy");
}

public int AddNumbers(int number1, int number2)
{
return number1 + number2;
}
}
}

Compile this. Create a new console application and copy the DLL which was created by the class library to debug folder of this application.
Your console application code should look like below.

Assembly myAssembly = Assembly.LoadFile(Environment.CurrentDirectory + "\\MyClassLibrary.dll"); // will load the assembly
Type ReflectionObject = myAssembly.GetType("MyClassLibrary.ReflectionClass"); //get the class name. it should be fully qualified. i.e with the namespace.
object classObject = Activator.CreateInstance(ReflectionObject); // create an instance of the type.
ReflectionObject.GetMethod("GetName").Invoke(classObject, null); // invoke the method without parameters
object returnValue = ReflectionObject.GetMethod("AddNumbers").Invoke(classObject, new object[] { 3, 4 }); // invoke the method with Parameter.
Console.WriteLine(returnValue.ToString());

If you have any queries, please do post it here.


Comments

Author: Jessie01 Jul 2008 Member Level: Gold   Points : 0

Its really brainstroming. :)



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: