Tuesday, April 19, 2011

What is Reflection Emit in console application:

Reflection Emit is a powerful technology that enables you to dynamically create methods, types, and assemblies at run time. Reflection Emit is enabled by a group of classes in the System.Reflection.Emit namespace that is referred to as builder classes because many of them have the suffix Builder in their name.

Reflection Emit is the technology through which programs can dynamically generate executable code at run time. By using Reflection Emit, you can code at run time anything that you could code at compile time.

•    Programs can generate assemblies, modules, type, type members, methods, metadata, and static methods.
•    Generated code can be transient(destroyed when the program ends or earlier)
•    Generated assemblies can be saved to disk for later use.

Dynamic methods:
•    Are lightweight stand- alone methods only.
•    Can be garbage collected to reclaim memory.
•    Cannot be saved to disk

Dynamic assemblies:

•    Have an identical structure to assemblies that are loaded from disk.
•    Are only cleaned up when the application domain unloads.
•    Can be saved to disk and loaded as normal assemblies                              

For example:

using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Reflection.Emit;
using System.Threading;   
namespace ConsoleApplication1
    class Program
        static void Main(string[] args)
            AssemblyName an = new AssemblyName();
            an.Name = "emitassembly";

            AppDomain ad = Thread.GetDomain();
            AssemblyBuilder ab = ad.DefineDynamicAssembly(an, AssemblyBuilderAccess.ReflectionOnly);

            ModuleBuilder mb;
            mb = ab.DefineDynamicModule("emitmodule", "emitmodule.mod");

            TypeBuilder t = mb.DefineType("sample", TypeAttributes.Public);

            MethodBuilder m = t.DefineMethod("fun", MethodAttributes.Public, typeof(void), null);

            ILGenerator mil = m.GetILGenerator();

            Type[] tp = new Type[1];
            tp[0] = typeof(String);
            MethodInfo wm = typeof(Console).GetMethod("WriteLine", tp);

            mil.Emit(OpCodes.Ldstr, "Hello");
            mil.Emit(OpCodes.Call, wm);

            AssemblyBuilder asb = (AssemblyBuilder)t.Assembly;

            //Calling sample
             sample s = new sample();


Output is display below: after the debug then create emitassembly.dll, emotmodule.mod, mod7less3.exe and mod7less3.pdb.

No comments:

Recent Posts