MethodBuilder Class

MethodBuilder Class

 

Defines and represents a method (or constructor) on a dynamic class.

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

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

[ClassInterfaceAttribute(ClassInterfaceType.None)]
[ComVisibleAttribute(true)]
[HostProtectionAttribute(SecurityAction.LinkDemand, MayLeakOnAbort = true)]
public sealed class MethodBuilder : MethodInfo, _MethodBuilder

NameDescription
System_CAPS_pubpropertyAttributes

Retrieves the attributes for this method.(Overrides MethodBase.Attributes.)

System_CAPS_pubpropertyCallingConvention

Returns the calling convention of the method.(Overrides MethodBase.CallingConvention.)

System_CAPS_pubpropertyContainsGenericParameters

Not supported for this type.(Overrides MethodBase.ContainsGenericParameters.)

System_CAPS_pubpropertyCustomAttributes

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

System_CAPS_pubpropertyDeclaringType

Returns the type that declares this method.(Overrides MemberInfo.DeclaringType.)

System_CAPS_pubpropertyInitLocals

Gets or sets a Boolean value that specifies whether the local variables in this method are zero initialized. The default value of this property is true.

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 a generic method.(Overrides MethodBase.IsGenericMethod.)

System_CAPS_pubpropertyIsGenericMethodDefinition

Gets a value indicating whether the current MethodBuilder object represents the definition of a generic method.(Overrides MethodBase.IsGenericMethodDefinition.)

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

Throws a NotSupportedException in all cases.(Overrides MethodBase.IsSecurityCritical.)

System_CAPS_pubpropertyIsSecuritySafeCritical

Throws a NotSupportedException in all cases. (Overrides MethodBase.IsSecuritySafeCritical.)

System_CAPS_pubpropertyIsSecurityTransparent

Throws a NotSupportedException in all cases. (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

Retrieves the internal handle for the method. Use this handle to access the underlying metadata handle.(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 in which the current method is being defined.(Overrides MemberInfo.Module.)

System_CAPS_pubpropertyName

Retrieves the name of this method.(Overrides MemberInfo.Name.)

System_CAPS_pubpropertyReflectedType

Retrieves the class that was used in reflection to obtain this object.(Overrides MemberInfo.ReflectedType.)

System_CAPS_pubpropertyReturnParameter

Gets a ParameterInfo object that contains information about the return type of the method, such as whether the return type has custom modifiers. (Overrides MethodInfo.ReturnParameter.)

System_CAPS_pubpropertyReturnType

Gets the return type of the method represented by this MethodBuilder.(Overrides MethodInfo.ReturnType.)

System_CAPS_pubpropertyReturnTypeCustomAttributes

Returns the custom attributes of the method's return type.(Overrides MethodInfo.ReturnTypeCustomAttributes.)

System_CAPS_pubpropertySignature

Retrieves the signature of the method.

NameDescription
System_CAPS_pubmethodAddDeclarativeSecurity(SecurityAction, PermissionSet)

Adds declarative security to this method.

System_CAPS_pubmethodCreateDelegate(Type)

Creates a delegate of the specified type from this method.(Inherited from MethodInfo.)

System_CAPS_pubmethodCreateDelegate(Type, Object)

Creates a delegate of the specified type with the specified target from this method.(Inherited from MethodInfo.)

System_CAPS_pubmethodCreateMethodBody(Byte[], Int32)

Creates the body of the method using a supplied byte array of Microsoft intermediate language (MSIL) instructions.

System_CAPS_pubmethodDefineGenericParameters(String[])

Sets the number of generic type parameters for the current method, specifies their names, and returns an array of GenericTypeParameterBuilder objects that can be used to define their constraints.

System_CAPS_pubmethodDefineParameter(Int32, ParameterAttributes, String)

Sets the parameter attributes and the name of a parameter of this method, or of the return value of this method. Returns a ParameterBuilder that can be used to apply custom attributes.

System_CAPS_pubmethodEquals(Object)

Determines whether the given object is equal to this instance.(Overrides MethodInfo.Equals(Object).)

System_CAPS_pubmethodGetBaseDefinition()

Return the base implementation for a method.(Overrides MethodInfo.GetBaseDefinition().)

System_CAPS_pubmethodGetCustomAttributes(Boolean)

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

System_CAPS_pubmethodGetCustomAttributes(Type, Boolean)

Returns the custom attributes identified by the given type.(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_pubmethodGetGenericArguments()

Returns an array of GenericTypeParameterBuilder objects that represent the type parameters of the method, if it is generic.(Overrides MethodInfo.GetGenericArguments().)

System_CAPS_pubmethodGetGenericMethodDefinition()

Returns this method.(Overrides MethodInfo.GetGenericMethodDefinition().)

System_CAPS_pubmethodGetHashCode()

Gets the hash code for this method.(Overrides MethodInfo.GetHashCode().)

System_CAPS_pubmethodGetILGenerator()

Returns an ILGenerator for this method with a default Microsoft intermediate language (MSIL) stream size of 64 bytes.

System_CAPS_pubmethodGetILGenerator(Int32)

Returns an ILGenerator for this method with the specified Microsoft intermediate language (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_pubmethodGetModule()

Returns a reference to the module that contains this method.

System_CAPS_pubmethodGetParameters()

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

System_CAPS_pubmethodGetToken()

Returns the MethodToken that represents the token for this method.

System_CAPS_pubmethodGetType()

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

System_CAPS_pubmethodInvoke(Object, BindingFlags, Binder, Object[], CultureInfo)

Dynamically invokes the method reflected by this instance on the given object, passing along the specified parameters, and under the constraints of the given binder.(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)

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

System_CAPS_pubmethodMakeGenericMethod(Type[])

Returns a generic method constructed from the current generic method definition using the specified generic type arguments.(Overrides MethodInfo.MakeGenericMethod(Type[]).)

System_CAPS_pubmethodSetCustomAttribute(ConstructorInfo, Byte[])

Sets a custom attribute using a specified custom attribute blob.

System_CAPS_pubmethodSetCustomAttribute(CustomAttributeBuilder)

Sets a custom attribute using a custom attribute builder.

System_CAPS_pubmethodSetImplementationFlags(MethodImplAttributes)

Sets the implementation flags for this method.

System_CAPS_pubmethodSetMarshal(UnmanagedMarshal)

Obsolete.Sets marshaling information for the return type of this method.

System_CAPS_pubmethodSetMethodBody(Byte[], Int32, Byte[], IEnumerable<ExceptionHandler>, IEnumerable<Int32>)

Creates the body of the method by using a specified byte array of Microsoft intermediate language (MSIL) instructions.

System_CAPS_pubmethodSetParameters(Type[])

Sets the number and types of parameters for a method.

System_CAPS_pubmethodSetReturnType(Type)

Sets the return type of the method.

System_CAPS_pubmethodSetSignature(Type, Type[], Type[], Type[], Type[][], Type[][])

Sets the method signature, including the return type, the parameter types, and the required and optional custom modifiers of the return type and parameter types.

System_CAPS_pubmethodSetSymCustomAttribute(String, Byte[])

Set a symbolic custom attribute using a blob.

System_CAPS_pubmethodToString()

Returns this MethodBuilder instance 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_MethodBuilder.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

Maps a set of names to a corresponding set of dispatch identifiers.

System_CAPS_pubinterfaceSystem_CAPS_privmethod_MethodBuilder.GetTypeInfo(UInt32, UInt32, IntPtr)

Retrieves the type information for an object, which can then be used to get the type information for an interface.

System_CAPS_pubinterfaceSystem_CAPS_privmethod_MethodBuilder.GetTypeInfoCount(UInt32)

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

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

Provides access to properties and methods exposed by an object.

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<T>()

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

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

The MethodBuilder class is used to fully describe a method in Microsoft intermediate language (MSIL), including the name, attributes, signature, and method body. It is used in conjunction with the TypeBuilder class to create classes at runtime.

You can use reflection emit to define global methods and to define methods as type members. The APIs that define methods return MethodBuilder objects.

A global method is defined by using the ModuleBuilder.DefineGlobalMethod method, which returns a MethodBuilder object.

Global methods must be static. If a dynamic module contains global methods, the ModuleBuilder.CreateGlobalFunctions method must be called before persisting the dynamic module or the containing dynamic assembly because the common language runtime postpones fixing up the dynamic module until all global functions have been defined.

A global native method is defined by using the ModuleBuilder.DefinePInvokeMethod method. Platform invoke (PInvoke) methods must not be declared abstract or virtual. The runtime sets the MethodAttributes.PinvokeImpl attribute for a platform invoke method.

A method is defined as a type member by using the TypeBuilder.DefineMethod method, which returns a MethodBuilder object.

The DefineParameter method is used to set the name and parameter attributes of a parameter, or of the return value. TheParameterBuilder object returned by this method represents a parameter or the return value. The ParameterBuilder object can be used to set the marshaling, to set the constant value, and to apply custom attributes.

Members of the MethodAttributes enumeration define the precise character of a dynamic method:

  • Although MethodBuilder is derived from MethodInfo, some of the abstract methods defined in the MethodInfo class are not fully implemented in MethodBuilder. These MethodBuilder methods throw the NotSupportedException. For example the MethodBuilder.Invoke method is not fully implemented. You can reflect on these methods by retrieving the enclosing type using the Type.GetType or Assembly.GetType methods.

  • Custom modifiers are supported starting with the .NET Framework version 2.0. They are not supported in earlier versions.

The following example uses the MethodBuilder class to create a method within a dynamic type.


using System;
using System.Reflection;
using System.Reflection.Emit;

class DemoMethodBuilder 
{
    public static void AddMethodDynamically (TypeBuilder myTypeBld,
                                             string mthdName,
                                             Type[] mthdParams, 
                                             Type returnType,
                                             string mthdAction) 
    {

        MethodBuilder myMthdBld = myTypeBld.DefineMethod(
                                             mthdName,
                                             MethodAttributes.Public |
                                             MethodAttributes.Static,
                                             returnType,
                                             mthdParams);        

        ILGenerator ILout = myMthdBld.GetILGenerator();

        int numParams = mthdParams.Length;

        for (byte x=0; x < numParams; x++) 
        {
            ILout.Emit(OpCodes.Ldarg_S, x);
        }

        if (numParams > 1) 
        {
            for (int y=0; y<(numParams-1); y++) 
            {
                switch (mthdAction) 
                {
                    case "A": ILout.Emit(OpCodes.Add);
                              break;
                    case "M": ILout.Emit(OpCodes.Mul);
                              break;
                    default: ILout.Emit(OpCodes.Add);
                              break;
                }
            }
        }
        ILout.Emit(OpCodes.Ret);
    }

    public static void Main()
    {
        AppDomain myDomain = AppDomain.CurrentDomain;
        AssemblyName asmName = new AssemblyName();
        asmName.Name = "MyDynamicAsm";

        AssemblyBuilder myAsmBuilder = myDomain.DefineDynamicAssembly(
                                       asmName, 
                                       AssemblyBuilderAccess.RunAndSave);

        ModuleBuilder myModule = myAsmBuilder.DefineDynamicModule("MyDynamicAsm",
                                                                  "MyDynamicAsm.dll");

        TypeBuilder myTypeBld = myModule.DefineType("MyDynamicType",
                                                    TypeAttributes.Public);           

        // Get info from the user to build the method dynamically.
        Console.WriteLine("Let's build a simple method dynamically!");
        Console.WriteLine("Please enter a few numbers, separated by spaces.");
        string inputNums = Console.ReadLine();
        Console.Write("Do you want to [A]dd (default) or [M]ultiply these numbers? ");
        string myMthdAction = Console.ReadLine().ToUpper();
        Console.Write("Lastly, what do you want to name your new dynamic method? ");
        string myMthdName = Console.ReadLine();

        // Process inputNums into an array and create a corresponding Type array 
        int index = 0;
        string[] inputNumsList = inputNums.Split();

        Type[] myMthdParams = new Type[inputNumsList.Length];
        object[] inputValsList = new object[inputNumsList.Length];


        foreach (string inputNum in inputNumsList) 
        {
            inputValsList[index] = (object)Convert.ToInt32(inputNum);
                myMthdParams[index] = typeof(int);
                index++;
        } 

        // Now, call the method building method with the parameters, passing the 
        // TypeBuilder by reference.
        AddMethodDynamically(myTypeBld,
                             myMthdName,
                             myMthdParams,
                             typeof(int),        
                             myMthdAction);

        Type myType = myTypeBld.CreateType();

        Console.WriteLine("---");
        Console.WriteLine("The result of {0} the inputted values is: {1}",
                          ((myMthdAction == "M") ? "multiplying" : "adding"),
                          myType.InvokeMember(myMthdName,
                          BindingFlags.InvokeMethod | BindingFlags.Public |
                          BindingFlags.Static,
                          null,
                          null,
                          inputValsList));
        Console.WriteLine("---");

        // Let's take a look at the method we created.
        // If you are interested in seeing the MSIL generated dynamically for the method
        // your program generated, change to the directory where you ran the compiled
        // code sample and type "ildasm MyDynamicAsm.dll" at the prompt. When the list
        // of manifest contents appears, click on "MyDynamicType" and then on the name of
        // of the method you provided during execution.

        myAsmBuilder.Save("MyDynamicAsm.dll");

        MethodInfo myMthdInfo = myType.GetMethod(myMthdName);
        Console.WriteLine("Your Dynamic Method: {0};", myMthdInfo.ToString());    
    }
}

.NET Framework
Available since 1.1
Silverlight
Available since 2.0

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