In this article we would learn how we can dynamically invoke a simple Method using Reflection .
Lets start off by creating a class with a simple method as shown below :
class A
{
public void display()
{
Console.WriteLine("Method Invoked");
}
}
Now my task is to invoke this method using Reflection.
I implement my Program class as shown below :
class Program
{
static void Main(string[] args)
{
A a = new A();
Type typObjectContext = a.GetType();
Type[] NoParams = { };
MethodInfo meth = typObjectContext.GetMethod("display", NoParams);
dynamic o2 = meth.Invoke(a, null);
Console.ReadLine();
}
Lets break down the code as shown below :
A a = new A();
I create a object of the class where the display method exist .
Type typObjectContext = a.GetType();
I then get the type of the object a which we just created . I assign the Type in Variable of type Type.
Since the display method does not take any parameter I can simply create a Type [] array as shown below :
Type[] NoParams = { };
Now lets get to the invoking of the method .
Before invoking we need to get the Method instance as shown below :
MethodInfo meth = typObjectContext.GetMethod("display", NoParams);
A method is invoked using Reflection as shown below :
dynamic o2 = meth.Invoke(a, null);
Run it .The method is invoked now .
I have defined a simple method without any parameters . This is enough as a starter. In future posts we will see how we can invoke more complex methods using Reflection .