Invoke an object's public methods by using their names in C#

You can use reflection to call an object's methods by using their names as shown in the following code.

// Invoke the method.
private void btnInvoke_Click(object sender, EventArgs e)
{
try
{
Type this_type = this.GetType();
MethodInfo method_info = this_type.GetMethod(txtMethodName.Text);
method_info.Invoke(this, null);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

The code uses GetType to get the class's type information. It then calls GetMethod to get a MethodInfo object describing the method. It calls that object's Invoke method to invoke the method. The second parameter to this call is an array of parameters that should be sent to the method call. The following code shows the methods available in this example.

// The public methods to invoke.
public void Method1()
{
MessageBox.Show("This is Method 1");
}
public void Method2()
{
MessageBox.Show("This is Method 2");
}

Reflection lets you do lots of other things with objects such as learn about and invoke their properties, methods, and events.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.