Wednesday, September 15, 2010

C# Dynamically execute a function from string

/**
* from other post (http://dotnet-anythingabout.blogspot.com/2010/09/dynamically-create-instance-of-object.html)
*/
String typeName = "Yournamespace.yourclassname";
Object objectInstance = Activator.CreateInstance(Type.GetType(typeName));

object[] parameters = new object[2]; /** or new object[] {"test","markg"} **/
parameters [0] ="test";
parameters [1] ="markg";
string methodName = "Add";

objectInstance .GetType().InvokeMember(methodName, BindingFlags.InvokeMethod, null, objectInstance , parameters);

OR

Type[] paramTypes = new Type[2];
paramTypes[0] = Type.GetType("System.String");
paramTypes[1] = Type.GetType("System.String");

MethodInfo methodInfo = objectInstance.GetType().GetMethod(methodName, paramTypes);
methodInfo.Invoke(objectInstance ,parameters);

No comments:

Post a Comment