Export (0) Print
Expand All

DynamicMethod.CreateDelegate Method (Type)

Note: This method is new in the .NET Framework version 2.0.

Completes the dynamic method and creates a delegate that can be used to execute it.

Namespace: System.Reflection.Emit
Assembly: mscorlib (in mscorlib.dll)

[ComVisibleAttribute(true)] 
public Delegate CreateDelegate (
	Type delegateType
)
/** @attribute ComVisibleAttribute(true) */ 
public Delegate CreateDelegate (
	Type delegateType
)
ComVisibleAttribute(true) 
public function CreateDelegate (
	delegateType : Type
) : Delegate

Parameters

delegateType

A delegate type whose signature matches that of the dynamic method.

Return Value

A delegate of the specified type, which can be used to execute the dynamic method.

Exception typeCondition

InvalidOperationException

The dynamic method has no method body.

ArgumentException

delegateType has the wrong number of parameters or the wrong parameter types.

Calling the CreateDelegate method or the Invoke method completes the dynamic method. Any further attempt to alter the dynamic method, such as modifying parameter definitions or emitting more Microsoft intermediate language (MSIL), is ignored; no exception is thrown.

To create a method body for a dynamic method when you have your own MSIL generator, call the GetDynamicILInfo method to obtain a DynamicILInfo object. If you do not have your own MSIL generator, call the GetILGenerator method to obtain an ILGenerator object that can be used to generate the method body.

The following code example creates a dynamic method that takes two parameters. The example emits a simple function body that prints the first parameter to the console, and the example uses the second parameter as the return value of the method. The example completes the method by creating a delegate, invokes the delegate with different parameters, and finally invokes the dynamic method using the Invoke method.

using System;
using System.Reflection;
using System.Reflection.Emit;
using Microsoft.VisualBasic;

public class Test
{
    // Declare a delegate that will be used to execute the completed
    // dynamic method. 
    private delegate int HelloInvoker(string msg, int ret);

    public static void Main()
    {
        // Create an array that specifies the types of the parameters
        // of the dynamic method. This method has a string parameter
        // and an int parameter.
        Type[] helloArgs = {typeof(string), typeof(int)};

        // Create a dynamic method with the name "Hello", a return type
        // of int, and two parameters whose types are specified by the
        // array helloArgs. Create the method in the module that
        // defines the Test class.
        DynamicMethod hello = new DynamicMethod("Hello", 
            typeof(int), 
            helloArgs, 
            typeof(Test).Module);

        // Create an array that specifies the parameter types of the
        // overload of Console.WriteLine to be used in Hello.
        Type[] writeStringArgs = {typeof(string)};
        // Get the overload of Console.WriteLine that has one
        // String parameter.
        MethodInfo writeString = 
            typeof(Console).GetMethod("WriteLine", writeStringArgs);

        // Get an ILGenerator and emit a body for the dynamic method.
        ILGenerator il = hello.GetILGenerator();
        // Load the first argument, which is a string, onto the stack.
        il.Emit(OpCodes.Ldarg_0);
        // Call the overload of Console.WriteLine that prints a string.
        il.EmitCall(OpCodes.Call, writeString, null);
        // The Hello method returns the value of the second argument;
        // to do this, load the onto the stack and return.
        il.Emit(OpCodes.Ldarg_1);
        il.Emit(OpCodes.Ret);

        // Create a delegate that represents the dynamic method. This
        // action completes the method, and any further attempts to
        // change the method will cause an exception.
        HelloInvoker hi = 
            (HelloInvoker) hello.CreateDelegate(typeof(HelloInvoker));

        // Use the delegate to execute the dynamic method. Save and
        // print the return value.
        int retval = hi("\r\nHello, World!", 42);
        Console.WriteLine("Executing delegate hi(\"Hello, World!\", 42) returned {0}",
            retval);

        // Do it again, with different arguments.
        retval = hi("\r\nHi, Mom!", 5280);
        Console.WriteLine("Executing delegate hi(\"Hi, Mom!\", 5280) returned {0}",
            retval);
        
        // Create an array of arguments to use with the Invoke method.
        object[] invokeArgs = {"\r\nHello, World!", 42};
        // Invoke the dynamic method using the arguments. This is much
        // slower than using the delegate, because you must create an
        // array to contain the arguments, and ValueType arguments
        // must be boxed.
        object objRet = hello.Invoke(null, invokeArgs);
        Console.WriteLine("hello.Invoke returned {0}", objRet);
    }
}

import System.*;
import System.Reflection.*;
import System.Reflection.Emit.*;
import Microsoft.VisualBasic.*;

public class Test
{
    /** @delegate 
     */
    // Declare a delegate that will be used to execute the completed
    // dynamic method. 
    private delegate int HelloInvoker(String msg, int ret);

    public static void main(String[] args)
    {
        // Create an array that specifies the types of the parameters
        // of the dynamic method. This method has a string parameter
        // and an int parameter.
        Type helloArgs[] =  { String.class.ToType(), int.class.ToType() };
        // Create a dynamic method with the name "Hello", a return type
        // of int, and two parameters whose types are specified by the
        // array helloArgs. Create the method in the module that
        // defines the Test class.
        DynamicMethod hello = new DynamicMethod("Hello", int.class.ToType(),
            helloArgs, Test.class.ToType().get_Module());
        // Create an array that specifies the parameter types of the
        // overload of Console.WriteLine to be used in Hello.
        Type writeStringArgs[] = { String.class.ToType() };
        // Get the overload of Console.WriteLine that has one
        // String parameter.
        MethodInfo writeString = Console.class.ToType().GetMethod("WriteLine",
            writeStringArgs);
        // Get an ILGenerator and emit a body for the dynamic method.
        ILGenerator il = hello.GetILGenerator();
        // Load the first argument, which is a string, onto the stack.
        il.Emit(OpCodes.Ldarg_0);
        // Call the overload of Console.WriteLine that prints a string.
        il.EmitCall(OpCodes.Call, writeString, null);
        // The Hello method returns the value of the second argument;
        // to do this, load the onto the stack and return.
        il.Emit(OpCodes.Ldarg_1);
        il.Emit(OpCodes.Ret);

        // Create a delegate that represents the dynamic method. This
        // action completes the method, and any further attempts to
        // change the method will cause an exception.
        HelloInvoker hi = (HelloInvoker)(hello.CreateDelegate(
            HelloInvoker.class.ToType()));

        // Use the delegate to execute the dynamic method. Save and
        // print the return value.
        int retval = hi.Invoke("\r\nHello, World!", 42);
        Console.WriteLine("Invoking delegate hi(\"Hello, World!\", 42) returned {0}",
            System.Convert.ToString(retval));

        // Do it again, with different arguments.
        retval = hi.Invoke("\r\nHi, Mom!", 5280);
        Console.WriteLine("Invoking delegate hi(\"Hi, Mom!\", 5280) returned {0}",
            System.Convert.ToString(retval));

        // Create an array of arguments to use with the Invoke method.
        Object invokeArgs[] =  { "\r\nHello, World!", (System.Int32)42 };
        // Invoke the dynamic method using the arguments. This is much
        // slower than using the delegate, because you must create an
        // array to contain the arguments, and ValueType arguments
        // must be boxed.
        Object objRet = hello.Invoke(null, invokeArgs);
        Console.WriteLine("hello.Invoke returned {0}", objRet);
    } //main 
} //Test

Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see System Requirements.

.NET Framework

Supported in: 2.0

Community Additions

ADD
Show:
© 2014 Microsoft