DynamicMethod Class

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)

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

<ComVisibleAttribute(True)>
Public NotInheritable Class DynamicMethod
	Inherits MethodInfo

NameDescription
System_CAPS_pubmethodDynamicMethod(String, MethodAttributes, CallingConventions, Type, Type(), Module, Boolean)

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.

System_CAPS_pubmethodDynamicMethod(String, MethodAttributes, CallingConventions, Type, Type(), Type, Boolean)

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.

System_CAPS_pubmethodDynamicMethod(String, Type, Type())

Initializes an anonymously hosted dynamic method, specifying the method name, return type, and parameter types.

System_CAPS_pubmethodDynamicMethod(String, Type, Type(), Boolean)

Initializes 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.

System_CAPS_pubmethodDynamicMethod(String, Type, Type(), Module)

Creates a dynamic method that is global to a module, specifying the method name, return type, parameter types, and module.

System_CAPS_pubmethodDynamicMethod(String, Type, Type(), Module, Boolean)

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.

System_CAPS_pubmethodDynamicMethod(String, Type, Type(), Type)

Creates a dynamic method, specifying the method name, return type, parameter types, and the type with which the dynamic method is logically associated.

System_CAPS_pubmethodDynamicMethod(String, Type, Type(), Type, Boolean)

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.

NameDescription
System_CAPS_pubpropertyAttributes

Gets the attributes specified when the dynamic method was created.(Overrides MethodBase.Attributes.)

System_CAPS_pubpropertyCallingConvention

Gets the calling convention specified when the dynamic method was created.(Overrides MethodBase.CallingConvention.)

System_CAPS_pubpropertyContainsGenericParameters

Gets a value indicating whether the generic method contains unassigned generic type parameters.(Inherited from MethodBase.)

System_CAPS_pubpropertyCustomAttributes

Gets a collection that contains this member's custom attributes.(Inherited from MemberInfo.)

System_CAPS_pubpropertyDeclaringType

Gets the type that declares the method, which is always null for dynamic methods.(Overrides MemberInfo.DeclaringType.)

System_CAPS_pubpropertyInitLocals

Gets or sets a value indicating whether the local variables in the method are zero-initialized.

System_CAPS_pubpropertyIsAbstract

Gets a value indicating whether the method is abstract.(Inherited from MethodBase.)

System_CAPS_pubpropertyIsAssembly

Gets a value indicating 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.)

System_CAPS_pubpropertyIsConstructor

Gets a value indicating whether the method is a constructor.(Inherited from MethodBase.)

System_CAPS_pubpropertyIsFamily

Gets a value indicating 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.)

System_CAPS_pubpropertyIsFamilyAndAssembly

Gets a value indicating 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.)

System_CAPS_pubpropertyIsFamilyOrAssembly

Gets a value indicating 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.)

System_CAPS_pubpropertyIsFinal

Gets a value indicating whether this method is final.(Inherited from MethodBase.)

System_CAPS_pubpropertyIsGenericMethod

Gets a value indicating whether the method is generic.(Inherited from MethodBase.)

System_CAPS_pubpropertyIsGenericMethodDefinition

Gets a value indicating whether the method is a generic method definition.(Inherited from MethodBase.)

System_CAPS_pubpropertyIsHideBySig

Gets a value indicating whether only a member of the same kind with exactly the same signature is hidden in the derived class.(Inherited from MethodBase.)

System_CAPS_pubpropertyIsPrivate

Gets a value indicating whether this member is private.(Inherited from MethodBase.)

System_CAPS_pubpropertyIsPublic

Gets a value indicating whether this is a public method.(Inherited from MethodBase.)

System_CAPS_pubpropertyIsSecurityCritical

Gets a value that indicates whether the current dynamic method is security-critical or security-safe-critical, and therefore can perform critical operations. (Overrides MethodBase.IsSecurityCritical.)

System_CAPS_pubpropertyIsSecuritySafeCritical

Gets a value that indicates whether the current dynamic method is security-safe-critical at the current trust level; that is, whether it can perform critical operations and can be accessed by transparent code. (Overrides MethodBase.IsSecuritySafeCritical.)

System_CAPS_pubpropertyIsSecurityTransparent

Gets a value that indicates whether the current dynamic method is transparent at the current trust level, and therefore cannot perform critical operations.(Overrides MethodBase.IsSecurityTransparent.)

System_CAPS_pubpropertyIsSpecialName

Gets a value indicating whether this method has a special name.(Inherited from MethodBase.)

System_CAPS_pubpropertyIsStatic

Gets a value indicating whether the method is static.(Inherited from MethodBase.)

System_CAPS_pubpropertyIsVirtual

Gets a value indicating whether the method is virtual.(Inherited from MethodBase.)

System_CAPS_pubpropertyMemberType

Gets a MemberTypes value indicating that this member is a method.(Inherited from MethodInfo.)

System_CAPS_pubpropertyMetadataToken

Gets a value that identifies a metadata element.(Inherited from MemberInfo.)

System_CAPS_pubpropertyMethodHandle

Not supported for dynamic methods.(Overrides MethodBase.MethodHandle.)

System_CAPS_pubpropertyMethodImplementationFlags

Gets the MethodImplAttributes flags that specify the attributes of a method implementation.(Inherited from MethodBase.)

System_CAPS_pubpropertyModule

Gets the module with which the dynamic method is logically associated.(Overrides MemberInfo.Module.)

System_CAPS_pubpropertyName

Gets the name of the dynamic method.(Overrides MemberInfo.Name.)

System_CAPS_pubpropertyReflectedType

Gets the class that was used in reflection to obtain the method.(Overrides MemberInfo.ReflectedType.)

System_CAPS_pubpropertyReturnParameter

Gets the return parameter of the dynamic method.(Overrides MethodInfo.ReturnParameter.)

System_CAPS_pubpropertyReturnType

Gets the type of return value for the dynamic method.(Overrides MethodInfo.ReturnType.)

System_CAPS_pubpropertyReturnTypeCustomAttributes

Gets the custom attributes of the return type for the dynamic method.(Overrides MethodInfo.ReturnTypeCustomAttributes.)

NameDescription
System_CAPS_pubmethodCreateDelegate(Type)

Completes the dynamic method and creates a delegate that can be used to execute it.(Overrides MethodInfo.CreateDelegate(Type).)

System_CAPS_pubmethodCreateDelegate(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).)

System_CAPS_pubmethodDefineParameter(Int32, ParameterAttributes, String)

Defines a parameter of the dynamic method.

System_CAPS_pubmethodEquals(Object)

Returns a value that indicates whether this instance is equal to a specified object.(Inherited from MethodInfo.)

System_CAPS_pubmethodGetBaseDefinition()

Returns the base implementation for the method.(Overrides MethodInfo.GetBaseDefinition().)

System_CAPS_pubmethodGetCustomAttributes(Boolean)

Returns all the custom attributes defined for the method.(Overrides MemberInfo.GetCustomAttributes(Boolean).)

System_CAPS_pubmethodGetCustomAttributes(Type, Boolean)

Returns the custom attributes of the specified type that have been applied to the method.(Overrides MemberInfo.GetCustomAttributes(Type, Boolean).)

System_CAPS_pubmethodGetCustomAttributesData()

Returns a list of CustomAttributeData objects representing data about the attributes that have been applied to the target member.(Inherited from MemberInfo.)

System_CAPS_pubmethodGetDynamicILInfo()

Returns a DynamicILInfo object that can be used to generate a method body from metadata tokens, scopes, and Microsoft intermediate language (MSIL) streams.

System_CAPS_pubmethodGetGenericArguments()

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.)

System_CAPS_pubmethodGetGenericMethodDefinition()

Returns a MethodInfo object that represents a generic method definition from which the current method can be constructed.(Inherited from MethodInfo.)

System_CAPS_pubmethodGetHashCode()

Returns the hash code for this instance.(Inherited from MethodInfo.)

System_CAPS_pubmethodGetILGenerator()

Returns a Microsoft intermediate language (MSIL) generator for the method with a default MSIL stream size of 64 bytes.

System_CAPS_pubmethodGetILGenerator(Int32)

Returns a Microsoft intermediate language (MSIL) generator for the method with the specified MSIL stream size.

System_CAPS_pubmethodGetMethodBody()

When overridden in a derived class, gets a MethodBody object that provides access to the MSIL stream, local variables, and exceptions for the current method.(Inherited from MethodBase.)

System_CAPS_pubmethodGetMethodImplementationFlags()

Returns the implementation flags for the method.(Overrides MethodBase.GetMethodImplementationFlags().)

System_CAPS_pubmethodGetParameters()

Returns the parameters of the dynamic method.(Overrides MethodBase.GetParameters().)

System_CAPS_pubmethodGetType()

Gets the Type of the current instance.(Inherited from Object.)

System_CAPS_pubmethodInvoke(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).)

System_CAPS_pubmethodInvoke(Object, Object())

Invokes the method or constructor represented by the current instance, using the specified parameters.(Inherited from MethodBase.)

System_CAPS_pubmethodIsDefined(Type, Boolean)

Indicates whether the specified custom attribute type is defined.(Overrides MemberInfo.IsDefined(Type, Boolean).)

System_CAPS_pubmethodMakeGenericMethod(Type())

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.)

System_CAPS_pubmethodToString()

Returns the signature of the method, represented as a string.(Overrides Object.ToString().)

NameDescription
System_CAPS_pubinterfaceSystem_CAPS_privmethod_MemberInfo.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

Maps a set of names to a corresponding set of dispatch identifiers.(Inherited from MemberInfo.)

System_CAPS_pubinterfaceSystem_CAPS_privmethod_MemberInfo.GetType()

Gets a Type object representing the MemberInfo class.(Inherited from MemberInfo.)

System_CAPS_pubinterfaceSystem_CAPS_privmethod_MemberInfo.GetTypeInfo(UInt32, UInt32, IntPtr)

Retrieves the type information for an object, which can then be used to get the type information for an interface.(Inherited from MemberInfo.)

System_CAPS_pubinterfaceSystem_CAPS_privmethod_MemberInfo.GetTypeInfoCount(UInt32)

Retrieves the number of type information interfaces that an object provides (either 0 or 1).(Inherited from MemberInfo.)

System_CAPS_pubinterfaceSystem_CAPS_privmethod_MemberInfo.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Provides access to properties and methods exposed by an object.(Inherited from MemberInfo.)

System_CAPS_pubinterfaceSystem_CAPS_privmethod_MethodBase.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

Maps a set of names to a corresponding set of dispatch identifiers.(Inherited from MethodBase.)

System_CAPS_pubinterfaceSystem_CAPS_privmethod_MethodBase.GetType()

For a description of this member, see _MethodBase.GetType.(Inherited from MethodBase.)

System_CAPS_pubinterfaceSystem_CAPS_privmethod_MethodBase.GetTypeInfo(UInt32, UInt32, IntPtr)

Retrieves the type information for an object, which can then be used to get the type information for an interface.(Inherited from MethodBase.)

System_CAPS_pubinterfaceSystem_CAPS_privmethod_MethodBase.GetTypeInfoCount(UInt32)

Retrieves the number of type information interfaces that an object provides (either 0 or 1).(Inherited from MethodBase.)

System_CAPS_pubinterfaceSystem_CAPS_privmethod_MethodBase.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Provides access to properties and methods exposed by an object.(Inherited from MethodBase.)

System_CAPS_pubinterfaceSystem_CAPS_privmethod_MethodInfo.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

Maps a set of names to a corresponding set of dispatch identifiers.(Inherited from MethodInfo.)

System_CAPS_pubinterfaceSystem_CAPS_privmethod_MethodInfo.GetType()

Provides access to the GetType method from COM.(Inherited from MethodInfo.)

System_CAPS_pubinterfaceSystem_CAPS_privmethod_MethodInfo.GetTypeInfo(UInt32, UInt32, IntPtr)

Retrieves the type information for an object, which can be used to get the type information for an interface.(Inherited from MethodInfo.)

System_CAPS_pubinterfaceSystem_CAPS_privmethod_MethodInfo.GetTypeInfoCount(UInt32)

Retrieves the number of type information interfaces that an object provides (either 0 or 1).(Inherited from MethodInfo.)

System_CAPS_pubinterfaceSystem_CAPS_privmethod_MethodInfo.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Provides access to properties and methods exposed by an object.(Inherited from MethodInfo.)

System_CAPS_pubinterfaceSystem_CAPS_privproperty_MethodBase.IsAbstract

For a description of this member, see _MethodBase.IsAbstract.(Inherited from MethodBase.)

System_CAPS_pubinterfaceSystem_CAPS_privproperty_MethodBase.IsAssembly

For a description of this member, see _MethodBase.IsAssembly.(Inherited from MethodBase.)

System_CAPS_pubinterfaceSystem_CAPS_privproperty_MethodBase.IsConstructor

For a description of this member, see _MethodBase.IsConstructor.(Inherited from MethodBase.)

System_CAPS_pubinterfaceSystem_CAPS_privproperty_MethodBase.IsFamily

For a description of this member, see _MethodBase.IsFamily.(Inherited from MethodBase.)

System_CAPS_pubinterfaceSystem_CAPS_privproperty_MethodBase.IsFamilyAndAssembly

For a description of this member, see _MethodBase.IsFamilyAndAssembly.(Inherited from MethodBase.)

System_CAPS_pubinterfaceSystem_CAPS_privproperty_MethodBase.IsFamilyOrAssembly

For a description of this member, see _MethodBase.IsFamilyOrAssembly.(Inherited from MethodBase.)

System_CAPS_pubinterfaceSystem_CAPS_privproperty_MethodBase.IsFinal

For a description of this member, see _MethodBase.IsFinal.(Inherited from MethodBase.)

System_CAPS_pubinterfaceSystem_CAPS_privproperty_MethodBase.IsHideBySig

For a description of this member, see _MethodBase.IsHideBySig.(Inherited from MethodBase.)

System_CAPS_pubinterfaceSystem_CAPS_privproperty_MethodBase.IsPrivate

For a description of this member, see _MethodBase.IsPrivate.(Inherited from MethodBase.)

System_CAPS_pubinterfaceSystem_CAPS_privproperty_MethodBase.IsPublic

For a description of this member, see _MethodBase.IsPublic.(Inherited from MethodBase.)

System_CAPS_pubinterfaceSystem_CAPS_privproperty_MethodBase.IsSpecialName

For a description of this member, see _MethodBase.IsSpecialName.(Inherited from MethodBase.)

System_CAPS_pubinterfaceSystem_CAPS_privproperty_MethodBase.IsStatic

For a description of this member, see _MethodBase.IsStatic.(Inherited from MethodBase.)

System_CAPS_pubinterfaceSystem_CAPS_privproperty_MethodBase.IsVirtual

For a description of this member, see _MethodBase.IsVirtual.(Inherited from MethodBase.)

NameDescription
System_CAPS_pubmethodGetCustomAttribute(Type)

Overloaded. Retrieves a custom attribute of a specified type that is applied to a specified member.(Defined by CustomAttributeExtensions.)

System_CAPS_pubmethodGetCustomAttribute(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.)

System_CAPS_pubmethodGetCustomAttribute(Of T)()

Overloaded. Retrieves a custom attribute of a specified type that is applied to a specified member.(Defined by CustomAttributeExtensions.)

System_CAPS_pubmethodGetCustomAttribute(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.)

System_CAPS_pubmethodGetCustomAttributes()

Overloaded. Retrieves a collection of custom attributes that are applied to a specified member.(Defined by CustomAttributeExtensions.)

System_CAPS_pubmethodGetCustomAttributes(Type)

Overloaded. Retrieves a collection of custom attributes of a specified type that are applied to a specified member.(Defined by CustomAttributeExtensions.)

System_CAPS_pubmethodGetCustomAttributes(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.)

System_CAPS_pubmethodGetRuntimeBaseDefinition()

Retrieves an object that represents the specified method on the direct or indirect base class where the method was first declared.(Defined by RuntimeReflectionExtensions.)

System_CAPS_pubmethodIsDefined(Type)

Overloaded. Indicates whether custom attributes of a specified type are applied to a specified member.(Defined by CustomAttributeExtensions.)

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.

A dynamic method can be anonymously hosted, or it can belogically associated with a module or with a type.

  • If the dynamic method is anonymously hosted, it is located in a system-provided assembly, and therefore is isolated from other code. By default, it does not have access to any non-public data. An anonymously hosted dynamic method can have restricted ability to skip the JIT compiler's visibility checks, if it has been granted ReflectionPermission with the ReflectionPermissionFlag.RestrictedMemberAccess flag. The trust level of the assembly whose non-public members are accessed by the dynamic method must be equal to, or a subset of, the trust level of the call stack that emitted the dynamic method. For more information about anonymously hosted dynamic methods, see Walkthrough: Emitting Code in Partial Trust Scenarios.

  • If the dynamic method is associated with a module that you specify, the dynamic method is effectively global to that module. It can access all types in the module and all internal (Friend in Visual Basic) members of the types. You can associate a dynamic method with any module, regardless of whether you created the module, provided that a demand for ReflectionPermission with the RestrictedMemberAccess flag can be satisfied by the call stack that includes your code. If the ReflectionPermissionFlag.MemberAccess flag is included in the grant, the dynamic method can skip the JIT compiler's visibility checks and access the private data of all types declared in the module or in any other module in any assembly.

    System_CAPS_noteNote

    When you specify the module with which a dynamic method is associated, that module must not be in the system-provided assembly that is used for anonymous hosting.

  • If the dynamic method is associated with a type that you specify, it has access to all members of the type, regardless of access level. In addition, JIT visibility checks can be skipped. This gives the dynamic method access to the private data of other types declared in the same module or in any other module in any assembly. You can associate a dynamic method with any type, but your code must be granted ReflectionPermission with both the RestrictedMemberAccess and MemberAccess flags.

The following table shows which types and members are accessible to an anonymously hosted dynamic method, with and without JIT visibility checks, depending on whether ReflectionPermission with the RestrictedMemberAccess flag is granted.

 

Without RestrictedMemberAccess

With RestrictedMemberAccess

Without skipping JIT visibility checks

Public members of public types in any assembly.

Public members of public types in any assembly.

Skipping JIT visibility checks, with restrictions

Public members of public types in any assembly.

All members of all types, only in assemblies whose trust levels are equal to or less than the trust level of the assembly that emitted the dynamic method.

System_CAPS_noteNote

Prior to the .NET Framework 2.0 Service Pack 1, emitting code required ReflectionPermission with the ReflectionPermissionFlag.ReflectionEmit flag. This permission is included by default in the FullTrust and LocalIntranet named permission sets, but not in the Internet permission set. Therefore, in earlier versions of the .NET Framework a library can be used with Internet permissions only if it has the SecurityCriticalAttribute attribute and also executes an Assert for ReflectionEmit. Such libraries require careful security review because coding errors could result in security holes. The .NET Framework 2.0 SP1 allows code to be emitted in partial trust scenarios without issuing any security demands, because generating code is not inherently a privileged operation. That is, the generated code has no more permissions than the assembly that emits it. This allows libraries that emit code to be security transparent and removes the need to assert ReflectionEmit, which simplifies the task of writing a secure library. To use this feature, your application should target the .NET Framework 3.5 or later.

The following table shows which types and members are accessible to a dynamic method that is associated with a module or with a type in a module.

 

Associated with module

Associated with type

Without skipping JIT visibility checks

Public and internal members of public, internal, and private types in the module.

Public members of public types in any assembly.

All members of the associated type. Public and internal members of all the other types in the module.

Public members of public types in any assembly.

Skipping JIT visibility checks

All members of all types in any assembly.

All members of all types in any assembly.

A dynamic method that is associated with a module has the permissions of that module. A dynamic method that is associated with a type has the permissions of the module containing that type.

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.

Although dynamic methods are static methods (Shared methods in Visual Basic), the relaxed rules for delegate binding introduced in the .NET Framework 2.0 allow a dynamic method to be bound to an object, so that it acts like an instance method when called using that delegate instance. An example that demonstrates this is provided for the CreateDelegate(Type, Object) method overload.

System_CAPS_noteNote

In the .NET Framework 2.0, 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.

The following list summarizes the conditions under which dynamic methods can contain unverifiable code. (For example, a dynamic method is unverifiable if its InitLocals property is set to false.)

  • A dynamic method that is associated with a security-critical assembly is also security-critical, and can skip verification. For example, an assembly without security attributes that is run as a desktop application is treated as security-critical by the runtime. If you associate a dynamic method with the assembly, the dynamic method can contain unverifiable code.

  • If a dynamic method that contains unverifiable code is associated with an assembly that has level 1 transparency, the just-in-time (JIT) compiler injects a security demand. The demand succeeds only if the dynamic method is executed by fully trusted code. See Security-Transparent Code, Level 1.

  • If a dynamic method that contains unverifiable code is associated with an assembly that has level 2 transparency (such as mscorlib.dll), it throws an exception (injected by the JIT compiler) instead of making a security demand. See Security-Transparent Code, Level 2.

  • An anonymously hosted dynamic method that contains unverifiable code always throws an exception. It can never skip verification, even if it is created and executed by fully trusted code.

The exception that is thrown for unverifiable code varies depending on the way the dynamic method is invoked. If you invoke a dynamic method by using a delegate returned from the CreateDelegate method, a VerificationException is thrown. If you invoke the dynamic method by using the Invoke method, a TargetInvocationException is thrown with an inner VerificationException.

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

Imports System
Imports System.Reflection
Imports System.Reflection.Emit
Imports Microsoft.VisualBasic
Imports System.Globalization

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

    Public Shared Sub Main()
        ' 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. Create the method in the module that
        ' defines the String class.
        Dim hello As New DynamicMethod("Hello", _
            GetType(Integer), _
            helloArgs, _
            GetType(String).Module)

        ' Create an array that specifies the parameter types of the
        ' overload of Console.WriteLine to be used in Hello.
        Dim writeStringArgs() As Type = {GetType(String)}
        ' Get the overload of Console.WriteLine that has one
        ' String parameter.
        Dim writeString As MethodInfo = GetType(Console). _
            GetMethod("WriteLine", writeStringArgs) 

        ' 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)
        ' Load the first argument, which is a string, onto the stack.
        il.Emit(OpCodes.Ldarg_0)
        ' Call the overload of Console.WriteLine that prints a string.
        il.EmitCall(OpCodes.Call, writeString, Nothing)
        ' The Hello method returns the value of the second argument;
        ' to do this, load the onto the stack and return.
        il.Emit(OpCodes.Ldarg_1)
        il.Emit(OpCodes.Ret)

        ' 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.
        Console.WriteLine(vbCrLf & "Use the delegate to execute the dynamic method:")
        Dim retval As Integer = hi(vbCrLf & "Hello, World!", 42)
        Console.WriteLine("Invoking delegate hi(""Hello, World!"", 42) returned: " _
            & retval & ".")

        ' Execute it again, with different arguments.
        retval = hi(vbCrLf & "Hi, Mom!", 5280)
        Console.WriteLine("Invoking delegate hi(""Hi, Mom!"", 5280) returned: " _
            & retval & ".")

        Console.WriteLine(vbCrLf & "Use the Invoke method to execute the dynamic method:")
        ' Create an array of arguments to use with the Invoke method.
        Dim invokeArgs() As Object = {vbCrLf & "Hello, World!", 42}
        ' Invoke the dynamic method using the arguments. This is much
        ' slower than using the delegate, because you must create an
        ' array to contain the arguments, and value-type arguments
        ' must be boxed.
        Dim objRet As Object = hello.Invoke(Nothing, _
            BindingFlags.ExactBinding, Nothing, invokeArgs, _
            New CultureInfo("en-us"))
        Console.WriteLine("hello.Invoke returned: {0}", objRet)

        Console.WriteLine(vbCrLf & _
            " ----- Display information about the dynamic method -----")
        ' Display MethodAttributes for the dynamic method, set when 
        ' the dynamic method was created.
        Console.WriteLine(vbCrLf & "Method Attributes: {0}", _
            hello.Attributes)

        ' Display the calling convention of the dynamic method, set when the 
        ' dynamic method was created.
        Console.WriteLine(vbCrLf & "Calling convention: {0}", _ 
            hello.CallingConvention)

        ' Display the declaring type, which is always Nothing for dynamic
        ' methods.
        If hello.DeclaringType Is Nothing Then
            Console.WriteLine(vbCrLf & "DeclaringType is always Nothing for dynamic methods.")
        Else
            Console.WriteLine("DeclaringType: {0}", hello.DeclaringType)
        End If

        ' Display the default value for InitLocals.
        If hello.InitLocals Then
            Console.Write(vbCrLf & "This method contains verifiable code.")
        Else
            Console.Write(vbCrLf & "This method contains unverifiable code.")
        End If
        Console.WriteLine(" (InitLocals = {0})", hello.InitLocals)

        ' Display the module specified when the dynamic method was created.
        Console.WriteLine(vbCrLf & "Module: {0}", hello.Module)

        ' Display the name specified when the dynamic method was created.
        ' Note that the name can be blank.
        Console.WriteLine(vbCrLf & "Name: {0}", hello.Name)

        ' For dynamic methods, the reflected type is always Nothing.
        If hello.ReflectedType Is Nothing Then
            Console.WriteLine(vbCrLf & "ReflectedType is Nothing.")
        Else
            Console.WriteLine(vbCrLf & "ReflectedType: {0}", _
                hello.ReflectedType)
        End If

        If hello.ReturnParameter Is Nothing Then
            Console.WriteLine(vbCrLf & "Method has no return parameter.")
        Else
            Console.WriteLine(vbCrLf & "Return parameter: {0}", _
                hello.ReturnParameter)
        End If

        ' If the method has no return type, ReturnType is System.Void.
        Console.WriteLine(vbCrLf & "Return type: {0}", hello.ReturnType)           

        ' 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
            Console.WriteLine("The method has no return type.")
        Else
            Dim caProvider As ICustomAttributeProvider = _
                hello.ReturnTypeCustomAttributes
            Dim returnAttributes() As Object = _
                caProvider.GetCustomAttributes(True)
            If returnAttributes.Length = 0 Then
                Console.WriteLine(vbCrLf _
                    & "The return type has no custom attributes.")
            Else
                Console.WriteLine(vbCrLf _
                    & "The return type has the following custom attributes:")
                For Each attr As Object In returnAttributes
                    Console.WriteLine(vbTab & attr.ToString())
                Next attr
            End If
        End If

        Console.WriteLine(vbCrLf & "ToString: " & hello.ToString())

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

' This code example produces the following output:
'
'Use the delegate to execute the dynamic method:
'
'Hello, World!
'Invoking delegate hi("Hello, World!", 42) returned: 42.
'
'Hi, Mom!
'Invoking delegate hi("Hi, Mom!", 5280) returned: 5280.
'
'Use the Invoke method to execute the dynamic method:
'
'Hello, World!
'hello.Invoke returned: 42
'
' ----- 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: CommonLanguageRuntimeLibrary
'
'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

Universal Windows Platform
Available since 10
.NET Framework
Available since 2.0
Portable Class Library
Supported in: portable .NET platforms
Silverlight
Available since 2.0
Windows Phone Silverlight
Available since 7.1

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

Return to top
Show:
© 2016 Microsoft