DynamicMethod Class

Microsoft Silverlight will reach end of support after October 2021. Learn more.

Defines and represents a dynamic method that can be compiled, executed, and discarded. Discarded methods are available for garbage collection.

Inheritance Hierarchy

System.Object
  System.Reflection.MemberInfo
    System.Reflection.MethodBase
      System.Reflection.MethodInfo
        System.Reflection.Emit.DynamicMethod

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

Syntax

'Declaration
<ComVisibleAttribute(True)> _
Public NotInheritable Class DynamicMethod _
    Inherits MethodInfo
[ComVisibleAttribute(true)]
public sealed class DynamicMethod : MethodInfo

The DynamicMethod type exposes the following members.

Constructors

  Name Description
Public methodSupported by Silverlight for Windows Phone DynamicMethod(String, Type, array<Type[]) Creates an anonymously hosted dynamic method, specifying the method name, return type, and parameter types.
Public methodSupported by Silverlight for Windows Phone DynamicMethod(String, Type, array<Type[], Module) Security Critical. Creates a dynamic method that is global to a module, specifying the method name, return type, parameter types, and module.
Public methodSupported by Silverlight for Windows Phone DynamicMethod(String, Type, array<Type[], Type) Security Critical. Creates a dynamic method, specifying the method name, return type, parameter types, and the type with which the dynamic method is logically associated.
Public methodSupported by Silverlight for Windows Phone DynamicMethod(String, Type, array<Type[], Boolean) Security Critical. Creates an anonymously hosted dynamic method, specifying the method name, return type, parameter types, and whether just-in-time (JIT) visibility checks should be skipped for types and members accessed by the Microsoft intermediate language (MSIL) of the dynamic method.
Public methodSupported by Silverlight for Windows Phone DynamicMethod(String, Type, array<Type[], Module, Boolean) Security Critical. Creates a dynamic method that is global to a module, specifying the method name, return type, parameter types, module, and whether just-in-time (JIT) visibility checks should be skipped for types and members accessed by the Microsoft intermediate language (MSIL) of the dynamic method.
Public methodSupported by Silverlight for Windows Phone DynamicMethod(String, Type, array<Type[], Type, Boolean) Security Critical. Creates a dynamic method, specifying the method name, return type, parameter types, the type with which the dynamic method is logically associated, and whether just-in-time (JIT) visibility checks should be skipped for types and members accessed by the Microsoft intermediate language (MSIL) of the dynamic method.
Public methodSupported by Silverlight for Windows Phone DynamicMethod(String, MethodAttributes, CallingConventions, Type, array<Type[], Module, Boolean) Security Critical. Creates a dynamic method that is global to a module, specifying the method name, attributes, calling convention, return type, parameter types, module, and whether just-in-time (JIT) visibility checks should be skipped for types and members accessed by the Microsoft intermediate language (MSIL) of the dynamic method.
Public methodSupported by Silverlight for Windows Phone DynamicMethod(String, MethodAttributes, CallingConventions, Type, array<Type[], Type, Boolean) Security Critical. Creates a dynamic method, specifying the method name, attributes, calling convention, return type, parameter types, the type with which the dynamic method is logically associated, and whether just-in-time (JIT) visibility checks should be skipped for types and members accessed by the Microsoft intermediate language (MSIL) of the dynamic method.

Top

Properties

  Name Description
Public propertySupported by Silverlight for Windows Phone Attributes Gets the attributes specified when the dynamic method was created. (Overrides MethodBase.Attributes.)
Public propertySupported by Silverlight for Windows Phone CallingConvention Gets the calling convention specified when the dynamic method was created. (Overrides MethodBase.CallingConvention.)
Public propertySupported by Silverlight for Windows Phone ContainsGenericParameters Gets a value that indicates whether the generic method contains unassigned generic type parameters. (Inherited from MethodBase.)

In Silverlight for Windows Phone, this member is overridden by ContainsGenericParameters.
Public propertySupported by Silverlight for Windows Phone DeclaringType Gets the type that declares the method, which is always nulla null reference (Nothing in Visual Basic) for dynamic methods. (Overrides MemberInfo.DeclaringType.)
Public propertySupported by Silverlight for Windows Phone InitLocals Gets or sets a value indicating whether the local variables in the method are zero-initialized.
Public propertySupported by Silverlight for Windows Phone IsAbstract Gets a value that indicates whether the method is abstract (MustInherit in Visual Basic). (Inherited from MethodBase.)
Public propertySupported by Silverlight for Windows Phone IsAssembly Gets a value that indicates whether the potential visibility of this method or constructor is described by MethodAttributes.Assembly; that is, the method or constructor is visible at most to other types in the same assembly, and is not visible to derived types outside the assembly. (Inherited from MethodBase.)
Public propertySupported by Silverlight for Windows Phone IsConstructor Gets a value that indicates whether the method is a constructor. (Inherited from MethodBase.)
Public propertySupported by Silverlight for Windows Phone IsFamily Gets a value that indicates whether the visibility of this method or constructor is described by MethodAttributes.Family; that is, the method or constructor is visible only within its class and derived classes. (Inherited from MethodBase.)
Public propertySupported by Silverlight for Windows Phone IsFamilyAndAssembly Gets a value that indicates whether the visibility of this method or constructor is described by MethodAttributes.FamANDAssem; that is, the method or constructor can be called by derived classes, but only if they are in the same assembly. (Inherited from MethodBase.)
Public propertySupported by Silverlight for Windows Phone IsFamilyOrAssembly Gets a value that indicates whether the potential visibility of this method or constructor is described by MethodAttributes.FamORAssem; that is, the method or constructor can be called by derived classes wherever they are, and by classes in the same assembly. (Inherited from MethodBase.)
Public propertySupported by Silverlight for Windows Phone IsFinal Gets a value that indicates whether this method is final (NotOverridable in Visual Basic). (Inherited from MethodBase.)
Public propertySupported by Silverlight for Windows Phone IsGenericMethod Gets a value that indicates whether the method is generic. (Inherited from MethodBase.)

In Silverlight for Windows Phone, this member is overridden by IsGenericMethod.
Public propertySupported by Silverlight for Windows Phone IsGenericMethodDefinition Gets a value that indicates whether the method is a generic method definition. (Inherited from MethodBase.)

In Silverlight for Windows Phone, this member is overridden by IsGenericMethodDefinition.
Public propertySupported by Silverlight for Windows Phone IsHideBySig Gets a value that indicates whether only a member of the same kind with exactly the same signature is hidden in the derived class. (Inherited from MethodBase.)
Public propertySupported by Silverlight for Windows Phone IsPrivate Gets a value that indicates whether this member is private. (Inherited from MethodBase.)
Public propertySupported by Silverlight for Windows Phone IsPublic Gets a value that indicates whether this is a public method. (Inherited from MethodBase.)
Public propertySupported by Silverlight for Windows Phone IsSpecialName Gets a value that indicates whether this method has a special name. (Inherited from MethodBase.)
Public propertySupported by Silverlight for Windows Phone IsStatic Gets a value that indicates whether the method is static (Shared in Visual Basic). (Inherited from MethodBase.)
Public propertySupported by Silverlight for Windows Phone IsVirtual Gets a value that indicates whether the method is virtual (Overridable in Visual Basic). (Inherited from MethodBase.)
Public propertySupported by Silverlight for Windows Phone MemberType Gets a MemberTypes value indicating that this member is a method. (Inherited from MethodInfo.)
Public propertySupported by Silverlight for Windows Phone MetadataToken Gets a value that identifies a metadata element. (Inherited from MemberInfo.)
Public propertySupported by Silverlight for Windows Phone MethodHandle Not supported for dynamic methods. (Overrides MethodBase.MethodHandle.)
Public propertySupported by Silverlight for Windows Phone Module Gets the module with which the dynamic method is logically associated. (Overrides MemberInfo.Module.)
Public propertySupported by Silverlight for Windows Phone Name Gets the name of the dynamic method. (Overrides MemberInfo.Name.)
Public propertySupported by Silverlight for Windows Phone ReflectedType Gets the class that was used in reflection to obtain the method. (Overrides MemberInfo.ReflectedType.)
Public propertySupported by Silverlight for Windows Phone ReturnParameter Gets the return parameter of the dynamic method. (Overrides MethodInfo.ReturnParameter.)
Public propertySupported by Silverlight for Windows Phone ReturnType Gets the type of return value for the dynamic method. (Overrides MethodInfo.ReturnType.)
Public propertySupported by Silverlight for Windows Phone ReturnTypeCustomAttributes Gets the custom attributes of the return type for the dynamic method. (Overrides MethodInfo.ReturnTypeCustomAttributes.)

Top

Methods

  Name Description
Public methodSupported by Silverlight for Windows Phone CreateDelegate(Type) Completes the dynamic method and creates a delegate of the specified type, which can be used to execute the dynamic method. (Overrides MethodInfo.CreateDelegate(Type).)
Public methodSupported by Silverlight for Windows Phone CreateDelegate(Type, Object) Completes the dynamic method and creates a delegate that can be used to execute it, specifying the delegate type and an object the delegate is bound to. (Overrides MethodInfo.CreateDelegate(Type, Object).)
Public methodSupported by Silverlight for Windows Phone DefineParameter Defines a parameter of the dynamic method.
Public methodSupported by Silverlight for Windows Phone Equals(Object) Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected methodSupported by Silverlight for Windows Phone Finalize Allows an object to try to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection. (Inherited from Object.)
Public methodSupported by Silverlight for Windows Phone GetBaseDefinition Returns the base implementation for the method. (Overrides MethodInfo.GetBaseDefinition().)
Public methodSupported by Silverlight for Windows Phone GetCustomAttributes(Boolean) Returns all the custom attributes defined for the method. (Overrides MemberInfo.GetCustomAttributes(Boolean).)
Public methodSupported by Silverlight for Windows Phone GetCustomAttributes(Type, Boolean) Returns the custom attributes of the specified type that have been applied to the method. (Overrides MemberInfo.GetCustomAttributes(Type, Boolean).)
Public methodSupported by Silverlight for Windows Phone GetGenericArguments Returns an array of Type objects that represent the type arguments of a generic method or the type parameters of a generic method definition. (Inherited from MethodInfo.)
Public methodSupported by Silverlight for Windows Phone GetGenericMethodDefinition Returns a MethodInfo object that represents a generic method definition from which the current method can be constructed. (Inherited from MethodInfo.)
Public methodSupported by Silverlight for Windows Phone GetHashCode Serves as a hash function for a particular type. (Inherited from Object.)
Public methodSupported by Silverlight for Windows Phone GetILGenerator() Returns a Microsoft intermediate language (MSIL) generator for the method with a default MSIL stream size of 64 bytes.
Public methodSupported by Silverlight for Windows Phone GetILGenerator(Int32) Returns a Microsoft intermediate language (MSIL) generator for the method with the specified MSIL stream size.
Public methodSupported by Silverlight for Windows Phone GetMethodImplementationFlags Returns the implementation flags for the method. (Overrides MethodBase.GetMethodImplementationFlags().)
Public methodSupported by Silverlight for Windows Phone GetParameters Returns the parameters of the dynamic method. (Overrides MethodBase.GetParameters().)
Public methodSupported by Silverlight for Windows Phone GetType Gets the Type of the current instance. (Inherited from Object.)
Public methodSupported by Silverlight for Windows Phone Invoke(Object, array<Object[]) Invokes the method or constructor represented by the current instance, using the specified parameters. (Inherited from MethodBase.)
Public methodSupported by Silverlight for Windows Phone Invoke(Object, BindingFlags, Binder, array<Object[], CultureInfo) Invokes the dynamic method using the specified parameters, under the constraints of the specified binder, with the specified culture information. (Overrides MethodBase.Invoke(Object, BindingFlags, Binder, array<Object[], CultureInfo).)
Public methodSupported by Silverlight for Windows Phone IsDefined Indicates whether the specified custom attribute type is defined. (Overrides MemberInfo.IsDefined(Type, Boolean).)
Public methodSupported by Silverlight for Windows Phone MakeGenericMethod Substitutes the elements of an array of types for the type parameters of the current generic method definition, and returns a MethodInfo object representing the resulting constructed method. (Inherited from MethodInfo.)
Protected methodSupported by Silverlight for Windows Phone MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)
Public methodSupported by Silverlight for Windows Phone ToString Returns the signature of the method, represented as a string. (Overrides Object.ToString().)

Top

Remarks

You can use the DynamicMethod class to generate and execute a method at run time, without having to generate a dynamic assembly and a dynamic type to contain the method. The executable code created by the just-in-time (JIT) compiler is reclaimed when the DynamicMethod object is reclaimed. Dynamic methods are the most efficient way to generate and execute small amounts of code.

In Silverlight-based applications, all dynamic methods are anonymously hosted. Anonymously hosted dynamic methods are located in a system-provided assembly, and therefore are isolated from other code. They do not have access to any non-public data. For more information about anonymously hosted dynamic methods, see How to: Define and Execute Dynamic Methods.

Dynamic methods and their parameters do not have to be named, but you can specify names to assist in debugging. Custom attributes are not supported on dynamic methods or their parameters.

NoteNote:

Dynamic methods do not support symbol information, that is, local variable names and line-number mapping. This limitation might be removed in a future version. You can use AssemblyBuilder during development to simplify debugging the generated Microsoft intermediate language (MSIL), and then switch to dynamic methods during final deployment, because the ILGenerator calls are the same in both cases.

Although dynamic methods behave like static methods (Shared methods in Visual Basic), the rules for delegate binding allow a dynamic method to be bound to an object, so that it acts like an instance method when it is called using that delegate instance. An example that demonstrates this is provided for the CreateDelegate(Type, Object) method overload. For more information about delegate binding rules, see the Delegate class.

Examples

The following example creates a dynamic method that takes two parameters. The example emits a simple function body that returns a formatted string. The first parameter is a string that the method embeds in the formatted string; the second parameter is an integer, which the method squares and then embeds in the formatted string. The example completes the method by creating a delegate, invokes the delegate with different parameters, and finally invokes the dynamic method by using the Invoke method.

Imports System.Reflection
Imports System.Reflection.Emit
Imports System.Globalization

Public Class Example
   ' Declare a delegate type that can be used to execute the completed
   ' dynamic method. 
   Private Delegate Function HelloDelegate(ByVal sendee As String, _
       ByVal square As Integer) As String

   Public Shared Sub Demo(ByVal outputBlock As System.Windows.Controls.TextBlock)
      ' Create an array that specifies the types of the parameters
      ' of the dynamic method. This dynamic method has a String
      ' parameter and an Integer parameter.
      Dim helloArgs() As Type = {GetType(String), GetType(Integer)}

      ' Create a dynamic method with the name "Hello", a return type
      ' of Integer, and two parameters whose types are specified by
      ' the array helloArgs. 
      Dim hello As New DynamicMethod("Hello", _
          GetType(String), _
          helloArgs)

      ' Create an array that specifies the parameter types of the
      ' overload of String.Format to be used in Hello.
      Dim formatStringArgs() As Type = { GetType(String), GetType(Object), _
                                 GetType(Object), GetType(Object) }
      Dim formatString As MethodInfo = GetType(String). _
          GetMethod("Format", formatStringArgs)

      ' Get an ILGenerator and emit a body for the dynamic method,
      ' using a stream size larger than the IL that will be
      ' emitted.
      Dim il As ILGenerator = hello.GetILGenerator(256)
      ' Push the format string for String.Format on the stack.
      il.Emit(OpCodes.Ldstr, "Hello, {0}, {1} squared is {2}!")
      ' Load the first argument, which is a string, onto the stack,
      ' as the second argument of String.Format.
      il.Emit(OpCodes.Ldarg_0)
      ' Load the second argument, and box it. This is the third argument
      ' of String.Format, and because it is a value type it must be boxed
      ' in order to pass it as an object.
      il.Emit(OpCodes.Ldarg_1)
      il.Emit(OpCodes.Box, GetType(Integer))
      ' Load the second argument twice more, as the arguments of the 
      ' multiply operation that will square it. 
      il.Emit(OpCodes.Ldarg_1)
      il.Emit(OpCodes.Ldarg_1)
      ' Multiply the last two arguments on the stack, leaving the 
      ' result on the stack. The result must be boxed, so it can be passed
      ' as the fourth argument of String.Format.
      il.Emit(OpCodes.Mul)
      il.Emit(OpCodes.Box, GetType(Integer))
      ' Call the overload of String.Format that prints a string, formatting
      ' it to include the next three objects on the stack.
      il.Emit(OpCodes.Call, formatString)
      ' The Hello method returns the formatted string, which is already
      ' on the stack after the call to String.Format.
      il.Emit(OpCodes.Ret)

      ' Add parameter information to the dynamic method. (This is not
      ' necessary, but can be useful for debugging.) For each parameter,
      ' identified by position, supply the parameter attributes and a 
      ' parameter name.
      hello.DefineParameter(1, ParameterAttributes.In, "message")
      hello.DefineParameter(2, ParameterAttributes.In, "valueToReturn")

      ' Create a delegate that represents the dynamic method. This
      ' action completes the method. Any further attempts to
      ' change the method are ignored.
      Dim hi As HelloDelegate = _
                 CType(hello.CreateDelegate(GetType(HelloDelegate)), HelloDelegate)

      ' Use the delegate to execute the dynamic method.
      outputBlock.Text &= vbLf & "Use the delegate to execute the dynamic method:" & vbLf
      outputBlock.Text &= "hi(""Dad"", 42) returned: '" _
                       & hi("Dad", 42) & "'" & vbLf
      ' Execute it again, with different arguments.
      outputBlock.Text &= "hi(""Mom"", 5280) returned:  '" _
                       & hi("Mom", 5280) & "'" & vbLf

      outputBlock.Text &= vbLf & "Use the Invoke method to execute the dynamic method:" & vbLf
      ' Create an array of arguments to use with the Invoke method.
      Dim invokeArgs() As Object = { "Mom", 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 value-type arguments
      ' must be boxed.
      Dim objRet As Object = hello.Invoke(Nothing, _
          BindingFlags.ExactBinding, Nothing, invokeArgs, _
          New CultureInfo("en-us"))
      outputBlock.Text &= "hello.Invoke(...) returned:  '" & objRet & "'" & vbLf

      outputBlock.Text &= vbCrLf & _
          " ----- Display information about the dynamic method -----" & vbLf
      ' Display MethodAttributes for the dynamic method, set when 
      ' the dynamic method was created.
      outputBlock.Text &= String.Format("Method Attributes: {0}", _
          hello.Attributes) & vbLf

      ' Display the calling convention of the dynamic method, set when the 
      ' dynamic method was created.
      outputBlock.Text &= String.Format("Calling convention: {0}", _
          hello.CallingConvention) & vbLf

      ' Display the declaring type, which is always Nothing for dynamic
      ' methods.
      If hello.DeclaringType Is Nothing Then
         outputBlock.Text &= "DeclaringType is always Nothing for dynamic methods." & vbLf
      Else
         outputBlock.Text += String.Format("DeclaringType: {0}", hello.DeclaringType) & vbLf
      End If

      ' Display the default value for InitLocals.
      If hello.InitLocals Then
         outputBlock.Text &= "This method contains verifiable code."
      Else
         outputBlock.Text &= "This method contains unverifiable code."
      End If
      outputBlock.Text += String.Format(" (InitLocals = {0})", hello.InitLocals) & vbLf

      ' Display the module specified when the dynamic method was created.
      outputBlock.Text += String.Format("Module: {0}", hello.Module) & vbLf

      ' Display the name specified when the dynamic method was created.
      ' Note that the name can be blank.
      outputBlock.Text += String.Format("Name: {0}", hello.Name) & vbLf

      ' For dynamic methods, the reflected type is always Nothing.
      If hello.ReflectedType Is Nothing Then
         outputBlock.Text &= "ReflectedType is Nothing." & vbLf
      Else
         outputBlock.Text &= String.Format("ReflectedType: {0}", _
             hello.ReflectedType) &vbLf
      End If

      If hello.ReturnParameter Is Nothing Then
         outputBlock.Text &= "Method has no return parameter." & vbLf
      Else
         outputBlock.Text &= String.Format("Return parameter: {0}", _
             hello.ReturnParameter) & vbLf
      End If

      ' If the method has no return type, ReturnType is System.Void.
      outputBlock.Text += String.Format("Return type: {0}", hello.ReturnType) & vbCrLf

      ' ReturnTypeCustomAttributes returns an ICustomeAttributeProvider
      ' that can be used to enumerate the custom attributes of the
      ' return value. At present, there is no way to set such custom
      ' attributes, so the list is empty.
      If hello.ReturnType Is GetType(System.Void) Then
         outputBlock.Text &= "The method has no return type." & vbLf
      Else
         Dim caProvider As ICustomAttributeProvider = _
             hello.ReturnTypeCustomAttributes
         Dim returnAttributes() As Object = _
             caProvider.GetCustomAttributes(True)
         If returnAttributes.Length = 0 Then
            outputBlock.Text &= "The return type has no custom attributes." & vbLf
         Else
            outputBlock.Text &= "The return type has the following custom attributes:" & vbLf
            For Each attr As Object In returnAttributes
               outputBlock.Text &= "     " & attr.ToString() & vbLf
            Next attr
         End If
      End If

      outputBlock.Text &= "ToString: " & hello.ToString() & vbLf

      ' Display parameter information.
      Dim parameters() As ParameterInfo = hello.GetParameters()
      outputBlock.Text &= "Parameters: name, type, ParameterAttributes" & vbLf
      For Each p As ParameterInfo In parameters
         outputBlock.Text &= String.Format("     {0}, {1}, {2}", _
             p.Name, p.ParameterType, p.Attributes) & vbLf
      Next p
   End Sub
End Class

' This code example produces the following output:
'
'Use the delegate to execute the dynamic method:
'hi("Dad", 42) returned:  'Hello, Dad, 42 squared is 1764!'
'hi("Mom", 5280) returned:  'Hello, Mom, 5280 squared is 27878400!'
'
'Use the Invoke method to execute the dynamic method:
'hello.Invoke returned:  'Hello, Mom, 42 squared is 1764!'
'
' ----- Display information about the dynamic method -----
'Method Attributes: PrivateScope, Public, Static
'Calling convention: Standard
'DeclaringType is always Nothing for dynamic methods.
'This method contains verifiable code. (InitLocals = True)
'Module: RefEmit_InMemoryManifestModule
'Name: Hello
'ReflectedType is Nothing.
'Method has no return parameter.
'Return type: System.Int32
'The return type has no custom attributes.
'ToString: Int32 Hello(System.String, Int32)
'Parameters: name, type, ParameterAttributes
'        message, System.String, In
'        valueToReturn, System.Int32, In
using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Globalization;

public class Example
{
   // Declare a delegate type that can be used to execute the completed
   // dynamic method. 
   private delegate string HelloDelegate(string sendee, int square);

   public static void Demo(System.Windows.Controls.TextBlock outputBlock)
   {
      // Create an array that specifies the types of the parameters
      // of the dynamic method. This dynamic method has a String
      // parameter and an Integer parameter.
      Type[] helloArgs = { typeof(string), typeof(int) };

      // Create a dynamic method with the name "Hello", a return type
      // of String, and two parameters whose types are specified by
      // the array helloArgs. 
      DynamicMethod hello = new DynamicMethod("Hello",
          typeof(string),
          helloArgs);

      // Create an array that specifies the parameter types of the
      // overload of String.Format to be used in Hello.
      Type[] formatStringArgs = { typeof(string), typeof(object), typeof(object), 
                                 typeof(object) };
      // Get the overload of String.Format that has one String 
      // parameter for the format, and three object parameters.
      MethodInfo formatString = typeof(String).GetMethod("Format",
          formatStringArgs);

      // Get an ILGenerator and emit a body for the dynamic method,
      // using a stream size larger than the IL that will be
      // emitted.
      ILGenerator il = hello.GetILGenerator(256);
      // Push the format string for String.Format on the stack.
      il.Emit(OpCodes.Ldstr, "Hello, {0}, {1} squared is {2}!");
      // Load the first argument, which is a string, onto the stack,
      // as the second argument of String.Format.
      il.Emit(OpCodes.Ldarg_0);
      // Load the second argument, and box it. This is the third argument
      // of String.Format, and because it is a value type it must be boxed
      // in order to pass it as an object.
      il.Emit(OpCodes.Ldarg_1);
      il.Emit(OpCodes.Box, typeof(int));
      // Load the second argument twice more, as the arguments of the 
      // multiply operation that will square it. 
      il.Emit(OpCodes.Ldarg_1);
      il.Emit(OpCodes.Ldarg_1);
      // Multiply the last two arguments on the stack, leaving the 
      // result on the stack. The result must be boxed, so it can be passed
      // as the fourth argument of String.Format.
      il.Emit(OpCodes.Mul);
      il.Emit(OpCodes.Box, typeof(int));
      // Call the overload of String.Format that prints a string, formatting
      // it to include the next three objects on the stack.
      il.Emit(OpCodes.Call, formatString);
      // The Hello method returns the formatted string, which is already
      // on the stack after the call to String.Format.
      il.Emit(OpCodes.Ret);

      // Add parameter information to the dynamic method. (This is not
      // necessary, but can be useful for debugging.) For each parameter,
      // identified by position, supply the parameter attributes and a 
      // parameter name.
      hello.DefineParameter(1, ParameterAttributes.In, "message");
      hello.DefineParameter(2, ParameterAttributes.In, "valueToReturn");

      // Create a delegate that represents the dynamic method. This
      // action completes the method. Any further attempts to
      // change the method are ignored.
      HelloDelegate hi =
          (HelloDelegate)hello.CreateDelegate(typeof(HelloDelegate));

      // Use the delegate to execute the dynamic method.
      outputBlock.Text += "\r\nUse the delegate to execute the dynamic method:" + "\n";
      outputBlock.Text += "hi(\"Dad\", 42) returned: '" 
                       + hi("Dad", 42) + "'\n";
      // Execute it again, with different arguments.
      outputBlock.Text += "hi(\"Mom\", 5280) returned:  '" 
                       + hi("Mom", 5280) + "'\n";

      outputBlock.Text += "\r\nUse the Invoke method to execute the dynamic method:" + "\n";
      // Create an array of arguments to use with the Invoke method.
      object[] invokeArgs = { "Mom", 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 value-type arguments
      // must be boxed.
      object objRet = hello.Invoke(null, BindingFlags.ExactBinding, null, invokeArgs, new CultureInfo("en-us"));
      outputBlock.Text += "hello.Invoke(...) returned:  '" + objRet + "'\n";

      outputBlock.Text += "\r\n ----- Display information about the dynamic method -----" + "\n";
      // Display MethodAttributes for the dynamic method, set when 
      // the dynamic method was created.
      outputBlock.Text += String.Format("Method Attributes: {0}", hello.Attributes) + "\n";

      // Display the calling convention of the dynamic method, set when the 
      // dynamic method was created.
      outputBlock.Text += String.Format("Calling convention: {0}", hello.CallingConvention) + "\n";

      // Display the declaring type, which is always null for dynamic
      // methods.
      if (hello.DeclaringType == null)
      {
         outputBlock.Text += "DeclaringType is always null for dynamic methods." + "\n";
      }
      else
      {
         outputBlock.Text += String.Format("DeclaringType: {0}", hello.DeclaringType) + "\n";
      }

      // Display the default value for InitLocals.
      if (hello.InitLocals)
      {
         outputBlock.Text += "This method contains verifiable code.";
      }
      else
      {
         outputBlock.Text += "This method contains unverifiable code.";
      }
      outputBlock.Text += String.Format(" (InitLocals = {0})", hello.InitLocals) + "\n";

      // Display the module specified when the dynamic method was created.
      outputBlock.Text += String.Format("Module: {0}", hello.Module) + "\n";

      // Display the name specified when the dynamic method was created.
      // Note that the name can be blank.
      outputBlock.Text += String.Format("Name: {0}", hello.Name) + "\n";

      // For dynamic methods, the reflected type is always null.
      if (hello.ReflectedType == null)
      {
         outputBlock.Text += "ReflectedType is null." + "\n";
      }
      else
      {
         outputBlock.Text += String.Format("ReflectedType: {0}", hello.ReflectedType) + "\n";
      }

      if (hello.ReturnParameter == null)
      {
         outputBlock.Text += "Method has no return parameter." + "\n";
      }
      else
      {
         outputBlock.Text += String.Format("Return parameter: {0}", hello.ReturnParameter) + "\n";
      }

      // If the method has no return type, ReturnType is System.Void.
      outputBlock.Text += String.Format("Return type: {0}", hello.ReturnType) + "\n";

      // ReturnTypeCustomAttributes returns an ICustomeAttributeProvider
      // that can be used to enumerate the custom attributes of the
      // return value. At present, there is no way to set such custom
      // attributes, so the list is empty.
      if (hello.ReturnType == typeof(void))
      {
         outputBlock.Text += "The method has no return type." + "\n";
      }
      else
      {
         ICustomAttributeProvider caProvider = hello.ReturnTypeCustomAttributes;
         object[] returnAttributes = caProvider.GetCustomAttributes(true);
         if (returnAttributes.Length == 0)
         {
            outputBlock.Text += "The return type has no custom attributes." + "\n";
         }
         else
         {
            outputBlock.Text += "The return type has the following custom attributes:" + "\n";
            foreach (object attr in returnAttributes)
            {
               outputBlock.Text += "     " + attr.ToString() + "\n";
            }
         }
      }

      outputBlock.Text += String.Format("ToString: {0}", hello.ToString()) + "\n";

      // Display parameter information.
      ParameterInfo[] parameters = hello.GetParameters();
      outputBlock.Text += String.Format("Parameters: name, type, ParameterAttributes") + "\n";
      foreach (ParameterInfo p in parameters)
      {
         outputBlock.Text += String.Format("     {0}, {1}, {2}",
             p.Name, p.ParameterType, p.Attributes) + "\n";
      }
   }
}

/* This code example produces the following output:

Use the delegate to execute the dynamic method:
hi("Dad", 42) returned:  'Hello, Dad, 42 squared is 1764!'
hi("Mom", 5280) returned:  'Hello, Mom, 5280 squared is 27878400!'

Use the Invoke method to execute the dynamic method:
hello.Invoke returned:  'Hello, Mom, 42 squared is 1764!'

 ----- Display information about the dynamic method -----
Method Attributes: PrivateScope, Public, Static
Calling convention: Standard
DeclaringType is always null for dynamic methods.
This method contains verifiable code. (InitLocals = True)
Module: RefEmit_InMemoryManifestModule
Name: Hello
ReflectedType is null.
Method has no return parameter.
Return type: System.Int32
The return type has no custom attributes.
ToString: Int32 Hello(System.String, Int32)
Parameters: name, type, ParameterAttributes
        sendee, System.String, In
        valueToSquare, System.Int32, In
 */

Version Information

Silverlight

Supported in: 5, 4, 3

Silverlight for Windows Phone

Supported in: Windows Phone OS 7.1

Platforms

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.