How do I automate the process of getting an instance created and its function executed dynamically?
Thanks
Edit: Need an option to pass parameters too. Thanks
How do I automate the process of getting an instance created and its function executed dynamically?
Thanks
Edit: Need an option to pass parameters too. Thanks
To pass the parameters dynamically Here I have taken params string[] args, because different functions have different number of parameters so.
Assuming that the method you want to invoke does not take any parameters:
To invoke a constructor, Activator.CreateInstance will do the trick. It has a bunch of overloads to make your life easier.
If your constructor is parameterless:
If you need parameters:
To invoke, a method, once you have the Type object you can call
GetMethod
to get the method, and thenInvoke
(with or without parameters) to invoke it. Should you need it, Invoke will also give you the return value of the function you're calling (or null if its a void method),For a slightly more detailed sample (paste into a console app and go):
Do you just want to call a parameterless constructor to create the instance? Is the type specified as a string as well, or can you make it a generic method? For example:
or
I think your problem is little too generic here, I am providing a solution with certain assumptions here.
Assumption: you have a typeName (string), methodName (string), and a parameter (of SomeType).
let me know know if my assumptions are wrong.