This topic has not yet been rated - Rate this topic

DynamicMethod Class

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

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

Namespace:  System.Reflection.Emit
Assembly:  mscorlib (in mscorlib.dll)
[ComVisibleAttribute(true)]
public sealed class DynamicMethod : MethodInfo

The DynamicMethod type exposes the following members.

  Name Description
Public method Supported by Silverlight for Windows Phone DynamicMethod(String, Type, Type[]) Creates an anonymously hosted dynamic method, specifying the method name, return type, and parameter types.
Public method Supported by Silverlight for Windows Phone DynamicMethod(String, Type, 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 method Supported by Silverlight for Windows Phone DynamicMethod(String, Type, 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 method Supported by Silverlight for Windows Phone DynamicMethod(String, Type, 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 method Supported by Silverlight for Windows Phone DynamicMethod(String, Type, 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 method Supported by Silverlight for Windows Phone DynamicMethod(String, Type, 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 method Supported by Silverlight for Windows Phone DynamicMethod(String, MethodAttributes, CallingConventions, Type, 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 method Supported by Silverlight for Windows Phone DynamicMethod(String, MethodAttributes, CallingConventions, Type, 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
  Name Description
Public property Supported by Silverlight for Windows Phone Attributes Gets the attributes specified when the dynamic method was created. (Overrides MethodBase.Attributes.)
Public property Supported by Silverlight for Windows Phone CallingConvention Gets the calling convention specified when the dynamic method was created. (Overrides MethodBase.CallingConvention.)
Public property Supported 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 property Supported by Silverlight for Windows Phone DeclaringType Gets the type that declares the method, which is always null for dynamic methods. (Overrides MemberInfo.DeclaringType.)
Public property Supported by Silverlight for Windows Phone InitLocals Gets or sets a value indicating whether the local variables in the method are zero-initialized.
Public property Supported by Silverlight for Windows Phone IsAbstract Gets a value that indicates whether the method is abstract (MustInherit in Visual Basic). (Inherited from MethodBase.)
Public property Supported 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 property Supported by Silverlight for Windows Phone IsConstructor Gets a value that indicates whether the method is a constructor. (Inherited from MethodBase.)
Public property Supported 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 property Supported 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 property Supported 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 property Supported by Silverlight for Windows Phone IsFinal Gets a value that indicates whether this method is final (NotOverridable in Visual Basic). (Inherited from MethodBase.)
Public property Supported 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 property Supported 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 property Supported 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 property Supported by Silverlight for Windows Phone IsPrivate Gets a value that indicates whether this member is private. (Inherited from MethodBase.)
Public property Supported by Silverlight for Windows Phone IsPublic Gets a value that indicates whether this is a public method. (Inherited from MethodBase.)
Public property Supported by Silverlight for Windows Phone IsSpecialName Gets a value that indicates whether this method has a special name. (Inherited from MethodBase.)
Public property Supported by Silverlight for Windows Phone IsStatic Gets a value that indicates whether the method is static (Shared in Visual Basic). (Inherited from MethodBase.)
Public property Supported by Silverlight for Windows Phone IsVirtual Gets a value that indicates whether the method is virtual (Overridable in Visual Basic). (Inherited from MethodBase.)
Public property Supported by Silverlight for Windows Phone MemberType Gets a MemberTypes value indicating that this member is a method. (Inherited from MethodInfo.)
Public property Supported by Silverlight for Windows Phone MetadataToken Gets a value that identifies a metadata element. (Inherited from MemberInfo.)
Public property Supported by Silverlight for Windows Phone MethodHandle Not supported for dynamic methods. (Overrides MethodBase.MethodHandle.)
Public property Supported by Silverlight for Windows Phone Module Gets the module with which the dynamic method is logically associated. (Overrides MemberInfo.Module.)
Public property Supported by Silverlight for Windows Phone Name Gets the name of the dynamic method. (Overrides MemberInfo.Name.)
Public property Supported by Silverlight for Windows Phone ReflectedType Gets the class that was used in reflection to obtain the method. (Overrides MemberInfo.ReflectedType.)
Public property Supported by Silverlight for Windows Phone ReturnParameter Gets the return parameter of the dynamic method. (Overrides MethodInfo.ReturnParameter.)
Public property Supported by Silverlight for Windows Phone ReturnType Gets the type of return value for the dynamic method. (Overrides MethodInfo.ReturnType.)
Public property Supported by Silverlight for Windows Phone ReturnTypeCustomAttributes Gets the custom attributes of the return type for the dynamic method. (Overrides MethodInfo.ReturnTypeCustomAttributes.)
Top
  Name Description
Public method Supported 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 method Supported 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 method Supported by Silverlight for Windows Phone DefineParameter Defines a parameter of the dynamic method.
Public method Supported by Silverlight for Windows Phone Equals(Object) Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected method Supported 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 method Supported by Silverlight for Windows Phone GetBaseDefinition Returns the base implementation for the method. (Overrides MethodInfo.GetBaseDefinition().)
Public method Supported by Silverlight for Windows Phone GetCustomAttributes(Boolean) Returns all the custom attributes defined for the method. (Overrides MemberInfo.GetCustomAttributes(Boolean).)
Public method Supported 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 method Supported 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 method Supported 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 method Supported by Silverlight for Windows Phone GetHashCode Serves as a hash function for a particular type. (Inherited from Object.)
Public method Supported 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 method Supported by Silverlight for Windows Phone GetILGenerator(Int32) Returns a Microsoft intermediate language (MSIL) generator for the method with the specified MSIL stream size.
Public method Supported by Silverlight for Windows Phone GetMethodImplementationFlags Returns the implementation flags for the method. (Overrides MethodBase.GetMethodImplementationFlags().)
Public method Supported by Silverlight for Windows Phone GetParameters Returns the parameters of the dynamic method. (Overrides MethodBase.GetParameters().)
Public method Supported by Silverlight for Windows Phone GetType Gets the Type of the current instance. (Inherited from Object.)
Public method Supported by Silverlight for Windows Phone Invoke(Object, Object[]) Invokes the method or constructor represented by the current instance, using the specified parameters. (Inherited from MethodBase.)
Public method Supported by Silverlight for Windows Phone Invoke(Object, BindingFlags, Binder, 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, Object[], CultureInfo).)
Public method Supported by Silverlight for Windows Phone IsDefined Indicates whether the specified custom attribute type is defined. (Overrides MemberInfo.IsDefined(Type, Boolean).)
Public method Supported 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 method Supported by Silverlight for Windows Phone MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)
Public method Supported by Silverlight for Windows Phone ToString Returns the signature of the method, represented as a string. (Overrides Object.ToString().)
Top

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.

Note Note:

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.

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.


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
 */


Silverlight

Supported in: 5, 4, 3

Silverlight for Windows Phone

Supported in: Windows Phone OS 7.1

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

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ