[C# Helper]
Index Books FAQ Contact About Rod
[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[Beginning Software Engineering]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Invoke public methods by using their names in C#

invoke public methods

You can use reflection to invoke public methods by using their names. The following code shows how the example program does this.

// 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, passing it the method's name, to get a MethodInfo object describing the method.

Next 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.

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

Download the example to experiment with it and to see additional details.

© 2009-2022 Rocky Mountain Computer Consulting, Inc. All rights reserved.