[C#] Invoke (Public) Static Member Dynamically By MethodName String Identifier

AceInfinity

Emeritus, Contributor
Joined
Feb 21, 2012
Posts
1,728
Location
Canada
So I came up with this little function fooling around in C# for the past 20 minutes, and I thought you guys might be interested in taking a look :)

Code:
private void invokeMethod(string methodname, object[] args)
{
	MethodInfo MI = typeof(MethodsClass).GetMethods().FirstOrDefault(m => m.Name == methodname && m.IsStatic);
	if (MI != null)
		MI.Invoke(null, args);
}

What this does here is grabs all the methods from my MethodsClass and finds the firstordefault 'match' by checking of the method name is equal to the methodname param as a string value for the void invokeMethod and if the method is static as boolean. From here if it's found something of that nature, then we invoke it with the arguments specified as object[] from the args param i've given to the main method.

To use this, create a class, i've named mine "MethodsClass", like so:
Code:
public class MethodsClass
{
	public static void MsgBox(string display, string title)
	{
		MessageBox.Show(display, title);
	}
}

Give it a few methods, and be sure to have them static. Now we can use something like the MsgBox method i've provided here:

Code:
invokeMethod(textBox1.Text, textBox2.Text.Split(','));

Where textbox1.Text is the methodname string value, and the textbox2.text split function identifies our args object[] for the params of the MessageBox.Show().

The result:
a5FWP.png
 

Has Sysnative Forums helped you? Please consider donating to help us support the site!

Back
Top