Browse DevX
Sign up for e-mail newsletters from DevX


Generate and Execute Dynamic Script With .NET

Use the System.Reflection classes in the .NET Framework to write, execute, and interact with code you write dynamically at run-time from your applications.


What You Need
To build the samples you need Visual Studio .NET and the .NET Framework (sp1). You should have an understanding of the .NET Framework and scripting on the Windows platform.

Reflection is a powerful tool in the .NET Framework that enables type discovery, the viewing of assembly metadata, and dynamic invocation of assembly code at runtime. You can also use reflection to create object instances from types at runtime using the System.Reflection.Emit namespace. Typically, you'd use these features for creating compilers, and building development tools for evaluating compiled code—but you can also use them for generating and processing scripts.

With the dynamic invocation functions available through reflection, you can create a reference to an assembly at runtime, determine what methods of that assembly are available, and to execute one of these methods. This can be very useful for late binding and for working with assembly code from third parties where different assembly versions expose different classes and methods, yet the management of that code is not under your control. But you can also use these techniques to support script creation by users or for referencing components that may not be available at compile time. In addition, this is a useful technique for executing code generated dynamically at runtime.

To apply the reflection techniques described effectively, you need to understand the System.Reflection namespace. In this article, I'll show you an example of dynamic script generation and invocation using Jscript.NET code.

Thanks for your registration, follow us on our social networks to keep up-to-date