Dynamic invocation in C#

Please let other users know how useful this tip is by rating it below. And, submit your own .NET tip or code here.

One very useful feature related to reflection is the ability to create objects dynamically and call methods on them. Class1.cs below has methods that will be dynamically invoked at runtime from the DynaInvoke.cs.


using System;
class Class1{
       public static String method1()
           return "I am Static method (method1) in class1";
       public String method2()
           return "I am a Instance Method (method2) in Class1";
       public String method3(String s)
          return "Hello " + s;

Save this file as Class1.cs and Compile c:/>csc /t:library Class1.cs.


using System;
using System.Reflection;
class DynamicInvoke
public static void Main(String [] args)

String path =  "Class1.dll"
Assembly a = Assembly.Load(path); 

//Invoking a static method
Type mm = a.GetType("Class1");
String i = (String) mm.InvokeMember ("method1",BindingFlags.Default | 
BindingFlags.InvokeMethod,null,null,new object [] {}); Console.WriteLine(i); 

//Invoking a non-static method
object o = Activator.CreateInstance(mm);
i = (String) mm.InvokeMember("method2",BindingFlags.Default | 
BindingFlags.InvokeMethod,null,o,new object [] {}); 

//Invoking a non-static method with parameters
object [] par = new object[] {"kunal"};
i = (String) mm.InvokeMember("method3",BindingFlags.Default |

Save this file as DynaInvoke.cs and Compile c:/>csc DynaInvoke.cs  and run C:>DynaInvoke.

This was first published in June 2003

There are Comments. Add yours.

TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to:

Disclaimer: Our Tips Exchange is a forum for you to share technical advice and expertise with your peers and to learn from other enterprise IT professionals. TechTarget provides the infrastructure to facilitate this sharing of information. However, we cannot guarantee the accuracy or validity of the material submitted. You agree that your use of the Ask The Expert services and your reliance on any questions, answers, information or other materials received through this Web site is at your own risk.