Resources » Code Snippets » Reflection

Invoke methods dynamically using reflection


Posted Date: 07-Mar-2007  Last Updated:   Category: Reflection    
Author: Member Level: Gold    Points: 10


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);
}
}


Did you like this resource? Share it with your friends and show your love!

Responses to "Invoke methods dynamically using reflection"
Author: Hetalkumar Kachhadiya    22 Oct 2010Member 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 abedi     09 Sep 2012
hi, If you want to dynamically call the class, what now, the class name as a string to pass to the function.


Feedbacks      

Post Comment:




  • 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:   Sign In to fill automatically.
    Email: (Will not be published, but required to validate comment)



    Type the numbers and letters shown on the left.


    Submit Article     Return to Article Index

    Subscribe to Subscribers
    Active Members
    TodayLast 7 Daysmore...

    Awards & Gifts
    Talk to Webmaster Tony John
    Copyright © SpiderWorks Technologies Pvt Ltd., Kochi, India