65.9K
CodeProject is changing. Read more.
Home

Run-Time Code Generation II: Invoke Methods using System.Reflection

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.74/5 (18 votes)

Dec 21, 2005

CPOL

1 min read

viewsIcon

74121

downloadIcon

374

Invoke methods using System.Reflection

Introduction

.NET provides mechanisms to compile source code and to use the generated assemblies within an application. Using these features, you can make applications more adaptive and more flexible.

This article shows how to invoke methods from an assembly using System.Reflection.

Necessary Using Statements

Before you start, add the following using statements to your application to ease the use of the namespaces:

using System.Reflection;
using System.Security.Permissions; 

Getting Started

At the beginning, you have to know which method from which type and from which module you want to call. Inspecting an assembly can be done very easily with System.Reflection too. But now we assume having all the knowledge about it because we generated it ourselves like in Run-Time Code Generation Part I.

So we just set the module's name, the type's name and the method's name:

string ModuleName = "TestAssembly.dll";
string TypeName = "TestClass";
string MethodName = "TestMethod";

Open an Assembly

Then you can open the assembly and set some Binding Flags, which are necessary for the instantiation of the chosen type:

Assembly myAssembly = Assembly.LoadFrom(ModuleName);

BindingFlags flags = (BindingFlags.NonPublic | BindingFlags.Public | 
  BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly);

Invoke a Method

After that, three loops are used to inspect the assembly and get the chosen module/type/method combination. Within the last loop, the type is instantiated and the method is called. The method can be called with parameters, but here we choose null for methods with no parameters. There can also be a response from the method, which we put into a general object.

Module [] myModules = myAssembly.GetModules();
foreach (Module Mo in myModules) 
    {
     if (Mo.Name == ModuleName) 
         {
         Type[] myTypes = Mo.GetTypes();
         foreach (Type Ty in myTypes)
             {
            if (Ty.Name == TypeName) 
                {
                MethodInfo[] myMethodInfo = Ty.GetMethods(flags);
                foreach(MethodInfo Mi in myMethodInfo)
                    {
                    if (Mi.Name == MethodName) 
                        {
                        Object obj = Activator.CreateInstance(Ty);
                        Object response = Mi.Invoke(obj, null);
                        }
                    }
                }
            }
        }
    }

Conclusion

With a few lines of code, you make your application call any method in any type from any module. In combination with code compilation, that is a powerful mechanism to enhance the adaptability of your applications.

References