DynamicMethod Class

July 28, 2014

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)

'Declaration
Public NotInheritable Class DynamicMethod _
	Inherits MethodInfo

The DynamicMethod type exposes the following members.

  NameDescription
Public methodDynamicMethod(String, Type, Type())Creates an anonymously hosted dynamic method, specifying the method name, return type, and parameter types.
Public methodDynamicMethod(String, Type, Type(), Boolean)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 methodDynamicMethod(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 methodDynamicMethod(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 methodDynamicMethod(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 methodDynamicMethod(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 methodDynamicMethod(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 methodDynamicMethod(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 propertyAttributesGets the attributes specified when the dynamic method was created. (Overrides MethodBase.Attributes.)
Public propertyCallingConventionGets the calling convention specified when the dynamic method was created. (Overrides MethodBase.CallingConvention.)
Public propertyContainsGenericParametersGets a value that indicates whether the generic method contains unassigned generic type parameters. (Inherited from MethodBase.)
Public propertyCustomAttributesGets a collection that contains this member's custom attributes. (Inherited from MemberInfo.)
Public propertyDeclaringTypeGets the type that declares the method, which is always Nothing for dynamic methods. (Overrides MemberInfo.DeclaringType.)
Public propertyInitLocalsGets or sets a value indicating whether the local variables in the method are zero-initialized.
Public propertyIsAbstractGets a value that indicates whether the method is abstract (MustInherit in Visual Basic). (Inherited from MethodBase.)
Public propertyIsAssemblyGets 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 propertyIsConstructorGets a value that indicates whether the method is a constructor. (Inherited from MethodBase.)
Public propertyIsFamilyGets 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 propertyIsFamilyAndAssemblyGets 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 propertyIsFamilyOrAssemblyGets 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 propertyIsFinalGets a value that indicates whether this method is final (NotOverridable in Visual Basic). (Inherited from MethodBase.)
Public propertyIsGenericMethodGets a value that indicates whether the method is generic. (Inherited from MethodBase.)
Public propertyIsGenericMethodDefinitionGets a value that indicates whether the method is a generic method definition. (Inherited from MethodBase.)
Public propertyIsHideBySigGets 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 propertyIsPrivateGets a value that indicates whether this member is private. (Inherited from MethodBase.)
Public propertyIsPublicGets a value that indicates whether this is a public method. (Inherited from MethodBase.)
Public propertyIsSpecialNameGets a value that indicates whether this method has a special name. (Inherited from MethodBase.)
Public propertyIsStaticGets a value that indicates whether the method is static (Shared in Visual Basic). (Inherited from MethodBase.)
Public propertyIsVirtualGets a value that indicates whether the method is virtual (Overridable in Visual Basic). (Inherited from MethodBase.)
Public propertyMemberTypeGets a MemberTypes value indicating that this member is a method. (Inherited from MethodInfo.)
Public propertyMetadataTokenGets a value that identifies a metadata element. (Inherited from MemberInfo.)
Public propertyMethodHandleNot supported for dynamic methods. (Overrides MethodBase.MethodHandle.)
Public propertyMethodImplementationFlagsGets the MethodImplAttributes flags that specify the attributes of a method implementation. (Inherited from MethodBase.)
Public propertyModuleGets the module with which the dynamic method is logically associated. (Overrides MemberInfo.Module.)
Public propertyNameGets the name of the dynamic method. (Overrides MemberInfo.Name.)
Public propertyReflectedTypeGets the class that was used in reflection to obtain the method. (Overrides MemberInfo.ReflectedType.)
Public propertyReturnParameterGets the return parameter of the dynamic method. (Overrides MethodInfo.ReturnParameter.)
Public propertyReturnTypeGets the type of return value for the dynamic method. (Overrides MethodInfo.ReturnType.)
Public propertyReturnTypeCustomAttributesGets the custom attributes of the return type for the dynamic method. (Overrides MethodInfo.ReturnTypeCustomAttributes.)
Top

  NameDescription
Public methodCreateDelegate(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 methodCreateDelegate(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 methodDefineParameterDefines a parameter of the dynamic method.
Public methodEqualsReturns a value that indicates whether this instance is equal to a specified object. (Inherited from MethodInfo.)
Protected methodFinalizeAllows an object to try to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection. (Inherited from Object.)
Public methodGetBaseDefinitionReturns the base implementation for the method. (Overrides MethodInfo.GetBaseDefinition.)
Public methodGetCustomAttributes(Boolean)Returns all the custom attributes defined for the method. (Overrides MemberInfo.GetCustomAttributes(Boolean).)
Public methodGetCustomAttributes(Type, Boolean)Returns the custom attributes of the specified type that have been applied to the method. (Overrides MemberInfo.GetCustomAttributes(Type, Boolean).)
Public methodGetGenericArgumentsReturns 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 methodGetGenericMethodDefinitionReturns a MethodInfo object that represents a generic method definition from which the current method can be constructed. (Inherited from MethodInfo.)
Public methodGetHashCodeReturns the hash code for this instance. (Inherited from MethodInfo.)
Public methodGetILGeneratorReturns a Microsoft intermediate language (MSIL) generator for the method with a default MSIL stream size of 64 bytes.
Public methodGetILGenerator(Int32)Returns a Microsoft intermediate language (MSIL) generator for the method with the specified MSIL stream size.
Public methodGetMethodImplementationFlagsReturns the implementation flags for the method. (Overrides MethodBase.GetMethodImplementationFlags.)
Public methodGetParametersReturns the parameters of the dynamic method. (Overrides MethodBase.GetParameters.)
Public methodGetTypeGets the Type of the current instance. (Inherited from Object.)
Public methodInvoke(Object, Object())Invokes the method or constructor represented by the current instance, using the specified parameters. (Inherited from MethodBase.)
Public methodInvoke(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 methodIsDefinedIndicates whether the specified custom attribute type is defined. (Overrides MemberInfo.IsDefined(Type, Boolean).)
Public methodMakeGenericMethodSubstitutes 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 methodMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Public methodToStringReturns the signature of the method, represented as a string. (Overrides Object.ToString.)
Top

  NameDescription
Public Extension MethodGetCustomAttribute(Type)Overloaded. Retrieves a custom attribute of a specified type that is applied to a specified member. (Defined by CustomAttributeExtensions.)
Public Extension MethodGetCustomAttribute(Type, Boolean)Overloaded. Retrieves a custom attribute of a specified type that is applied to a specified member, and optionally inspects the ancestors of that member. (Defined by CustomAttributeExtensions.)
Public Extension MethodGetCustomAttribute(Of T)Overloaded. Retrieves a custom attribute of a specified type that is applied to a specified member. (Defined by CustomAttributeExtensions.)
Public Extension MethodGetCustomAttribute(Of T)(Boolean)Overloaded. Retrieves a custom attribute of a specified type that is applied to a specified member, and optionally inspects the ancestors of that member. (Defined by CustomAttributeExtensions.)
Public Extension MethodGetCustomAttributesOverloaded. Retrieves a collection of custom attributes that are applied to a specified member. (Defined by CustomAttributeExtensions.)
Public Extension MethodGetCustomAttributes(Type)Overloaded. Retrieves a collection of custom attributes of a specified type that are applied to a specified member. (Defined by CustomAttributeExtensions.)
Public Extension MethodGetCustomAttributes(Of T)Overloaded. Retrieves a collection of custom attributes of a specified type that are applied to a specified member. (Defined by CustomAttributeExtensions.)
Public Extension MethodGetCustomAttributes(Of T)(Boolean)Overloaded. Retrieves a collection of custom attributes of a specified type that are applied to a specified member, and optionally inspects the ancestors of that member. (Defined by CustomAttributeExtensions.)
Public Extension MethodGetRuntimeBaseDefinitionRetrieves an object that represents the specified method on the direct or indirect base class where the method was first declared. (Defined by RuntimeReflectionExtensions.)
Public Extension MethodIsDefinedIndicates whether custom attributes of a specified type are applied to a specified member. (Defined by CustomAttributeExtensions.)
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 Windows Phone 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.

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.

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.


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


Windows Phone OS

Supported in: 8.1, 8.0, 7.1

Windows Phone

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

Show:
© 2014 Microsoft