Export (0) Print
Expand All
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.

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

The DynamicMethod type exposes the following members.

  NameDescription
Public methodSupported by Silverlight for Windows PhoneDynamicMethod(String, Type, Type[])Creates an anonymously hosted dynamic method, specifying the method name, return type, and parameter types.
Public methodSupported by Silverlight for Windows PhoneDynamicMethod(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 methodSupported by Silverlight for Windows PhoneDynamicMethod(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 methodSupported by Silverlight for Windows PhoneDynamicMethod(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 methodSupported by Silverlight for Windows PhoneDynamicMethod(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 methodSupported by Silverlight for Windows PhoneDynamicMethod(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 methodSupported by Silverlight for Windows PhoneDynamicMethod(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 methodSupported by Silverlight for Windows PhoneDynamicMethod(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
  NameDescription
Public propertySupported by Silverlight for Windows PhoneAttributesGets the attributes specified when the dynamic method was created. (Overrides MethodBase.Attributes.)
Public propertySupported by Silverlight for Windows PhoneCallingConventionGets the calling convention specified when the dynamic method was created. (Overrides MethodBase.CallingConvention.)
Public propertySupported by Silverlight for Windows PhoneContainsGenericParametersGets 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 PhoneDeclaringTypeGets the type that declares the method, which is always null for dynamic methods. (Overrides MemberInfo.DeclaringType.)
Public propertySupported by Silverlight for Windows PhoneInitLocalsGets or sets a value indicating whether the local variables in the method are zero-initialized.
Public propertySupported by Silverlight for Windows PhoneIsAbstractGets a value that indicates whether the method is abstract (MustInherit in Visual Basic). (Inherited from MethodBase.)
Public propertySupported by Silverlight for Windows PhoneIsAssemblyGets 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 PhoneIsConstructorGets a value that indicates whether the method is a constructor. (Inherited from MethodBase.)
Public propertySupported by Silverlight for Windows PhoneIsFamilyGets 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 PhoneIsFamilyAndAssemblyGets 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 PhoneIsFamilyOrAssemblyGets 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 PhoneIsFinalGets a value that indicates whether this method is final (NotOverridable in Visual Basic). (Inherited from MethodBase.)
Public propertySupported by Silverlight for Windows PhoneIsGenericMethodGets 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 PhoneIsGenericMethodDefinitionGets 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 PhoneIsHideBySigGets 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 PhoneIsPrivateGets a value that indicates whether this member is private. (Inherited from MethodBase.)
Public propertySupported by Silverlight for Windows PhoneIsPublicGets a value that indicates whether this is a public method. (Inherited from MethodBase.)
Public propertySupported by Silverlight for Windows PhoneIsSpecialNameGets a value that indicates whether this method has a special name. (Inherited from MethodBase.)
Public propertySupported by Silverlight for Windows PhoneIsStaticGets a value that indicates whether the method is static (Shared in Visual Basic). (Inherited from MethodBase.)
Public propertySupported by Silverlight for Windows PhoneIsVirtualGets a value that indicates whether the method is virtual (Overridable in Visual Basic). (Inherited from MethodBase.)
Public propertySupported by Silverlight for Windows PhoneMemberTypeGets a MemberTypes value indicating that this member is a method. (Inherited from MethodInfo.)
Public propertySupported by Silverlight for Windows PhoneMetadataTokenGets a value that identifies a metadata element. (Inherited from MemberInfo.)
Public propertySupported by Silverlight for Windows PhoneMethodHandleNot supported for dynamic methods. (Overrides MethodBase.MethodHandle.)
Public propertySupported by Silverlight for Windows PhoneModuleGets the module with which the dynamic method is logically associated. (Overrides MemberInfo.Module.)
Public propertySupported by Silverlight for Windows PhoneNameGets the name of the dynamic method. (Overrides MemberInfo.Name.)
Public propertySupported by Silverlight for Windows PhoneReflectedTypeGets the class that was used in reflection to obtain the method. (Overrides MemberInfo.ReflectedType.)
Public propertySupported by Silverlight for Windows PhoneReturnParameterGets the return parameter of the dynamic method. (Overrides MethodInfo.ReturnParameter.)
Public propertySupported by Silverlight for Windows PhoneReturnTypeGets the type of return value for the dynamic method. (Overrides MethodInfo.ReturnType.)
Public propertySupported by Silverlight for Windows PhoneReturnTypeCustomAttributesGets the custom attributes of the return type for the dynamic method. (Overrides MethodInfo.ReturnTypeCustomAttributes.)
Top
  NameDescription
Public methodSupported by Silverlight for Windows PhoneCreateDelegate(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 PhoneCreateDelegate(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 PhoneDefineParameterDefines a parameter of the dynamic method.
Public methodSupported by Silverlight for Windows PhoneEquals(Object)Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected methodSupported by Silverlight for Windows PhoneFinalizeAllows 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 PhoneGetBaseDefinitionReturns the base implementation for the method. (Overrides MethodInfo.GetBaseDefinition().)
Public methodSupported by Silverlight for Windows PhoneGetCustomAttributes(Boolean)Returns all the custom attributes defined for the method. (Overrides MemberInfo.GetCustomAttributes(Boolean).)
Public methodSupported by Silverlight for Windows PhoneGetCustomAttributes(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 PhoneGetGenericArgumentsReturns 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 PhoneGetGenericMethodDefinitionReturns 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 PhoneGetHashCodeServes as a hash function for a particular type. (Inherited from Object.)
Public methodSupported by Silverlight for Windows PhoneGetILGenerator()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 PhoneGetILGenerator(Int32)Returns a Microsoft intermediate language (MSIL) generator for the method with the specified MSIL stream size.
Public methodSupported by Silverlight for Windows PhoneGetMethodImplementationFlagsReturns the implementation flags for the method. (Overrides MethodBase.GetMethodImplementationFlags().)
Public methodSupported by Silverlight for Windows PhoneGetParametersReturns the parameters of the dynamic method. (Overrides MethodBase.GetParameters().)
Public methodSupported by Silverlight for Windows PhoneGetTypeGets the Type of the current instance. (Inherited from Object.)
Public methodSupported by Silverlight for Windows PhoneInvoke(Object, Object[])Invokes the method or constructor represented by the current instance, using the specified parameters. (Inherited from MethodBase.)
Public methodSupported by Silverlight for Windows PhoneInvoke(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 methodSupported by Silverlight for Windows PhoneIsDefinedIndicates whether the specified custom attribute type is defined. (Overrides MemberInfo.IsDefined(Type, Boolean).)
Public methodSupported by Silverlight for Windows PhoneMakeGenericMethodSubstitutes 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 PhoneMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Public methodSupported by Silverlight for Windows PhoneToStringReturns 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.

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.

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)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.