Invoke methods dynamically using reflection


This article help us about Invoke methods dynamically using reflection and how to use it.

Here's a simple example of Reflection which is used to invoke the method of an instance. MethodInfo class is used to access the specific method of the instance, using this class we can invoke the methods even if it has parameters. This is very help full when you are using late binding.

The following class has number of methods which we are going to invoke using reflection


public class AirCraft
{
private string m_Name;
public string Name
{
get { return m_Name; }
set { m_Name = value; }
}

private int m_Speed;

public int Speed
{
get { return m_Speed; }
set { m_Speed = value; }
}

public void ShowName()
{
MessageBox.Show("Aircraft name is " + Name);
}

public void StartFly()
{
MessageBox.Show(Name+" Is Flying...(Speed:"+Speed+" km/h)");
}

public void StopFly()
{
MessageBox.Show(Name+" Landed Safely");
}
}


implemeting the reflection concept to invoke the method of an instance


public class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
AirCraft obj = new AirCraft();
obj.Name = "Black Bird";
obj.Speed = 1000;
InvokeMethod(obj, "ShowName");
InvokeMethod(obj, "StartFly");
InvokeMethod(obj, "StopFly");
}

private void InvokeMethod(object instance,string methodName)
{
//Getting the method information using the method info class
MethodInfo mi = instance.GetType().GetMethod(methodName);

//invoing the method
//null- no parameter for the function [or] we can pass the array of parameters
mi.Invoke(instance, null);
}
}


Comments

Author: Hetalkumar Kachhadiya22 Oct 2010 Member Level: Gold   Points : 1

Visit the following link for the answer of your query:

http://www.dotnetspider.com/resources/4634-Invoke-me-ods-dynamically-using-reflection.aspx

Guest Author: mohammad abedi09 Sep 2012

hi, If you want to dynamically call the class, what now, the class name as a string to pass to the function.



  • 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: