Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All

MethodBuilder Class

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

For a list of all members of this type, see MethodBuilder Members.

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

[Visual Basic]
NotInheritable Public Class MethodBuilder
   Inherits MethodInfo
[C#]
public sealed class MethodBuilder : MethodInfo
[C++]
public __gc __sealed class MethodBuilder : public MethodInfo
[JScript]
public class MethodBuilder extends MethodInfo

Thread Safety

Reflection Emit is thread-safe when using assemblies that were created with the AppDomain.DefineDynamicAssembly method with the Boolean parameter isSynchronized set to true.

Remarks

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

Example

[Visual Basic, C#, C++] An example using the MethodBuilder class to create a method within a dynamic type is provided below.

[Visual Basic] 
Imports System
Imports System.Threading
Imports System.Reflection
Imports System.Reflection.Emit

 _


Class DemoMethodBuilder
   
   Public Shared Sub AddMethodDynamically(ByRef myTypeBld As TypeBuilder, _
                        mthdName As String, _
                            mthdParams() As Type, _
                            returnType As Type, _
                            mthdAction As String)
      
      Dim myMthdBld As MethodBuilder = myTypeBld.DefineMethod(mthdName, _
                       MethodAttributes.Public Or MethodAttributes.Static, _
                       returnType, _
                       mthdParams)
      
      Dim ILout As ILGenerator = myMthdBld.GetILGenerator()
      
      Dim numParams As Integer = mthdParams.Length
      
      Dim x As Byte
      For x = 0 To numParams - 1
         ILout.Emit(OpCodes.Ldarg_S, x)
      Next x
      
      If numParams > 1 Then
         Dim y As Integer
         For y = 0 To (numParams - 1) - 1
            Select Case mthdAction
               Case "A"
                  ILout.Emit(OpCodes.Add)
               Case "M"
                  ILout.Emit(OpCodes.Mul)
               Case Else
                  ILout.Emit(OpCodes.Add)
            End Select
         Next y
      End If
      ILout.Emit(OpCodes.Ret)
   End Sub 'AddMethodDynamically
    
   
   Public Shared Sub Main()
      
      Dim myDomain As AppDomain = Thread.GetDomain()
      Dim asmName As New AssemblyName()
      asmName.Name = "DynamicAssembly1"
      
      Dim myAsmBuilder As AssemblyBuilder = myDomain.DefineDynamicAssembly(asmName, _
                        AssemblyBuilderAccess.RunAndSave)
      
      Dim myModule As ModuleBuilder = myAsmBuilder.DefineDynamicModule("DynamicModule1", _
                                       "MyDynamicAsm.dll")
      
      Dim myTypeBld As TypeBuilder = 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.")
      Dim inputNums As String = Console.ReadLine()
      Console.Write("Do you want to [A]dd or [M]ultiply these numbers? ")
      Dim myMthdAction As String = Console.ReadLine()
      Console.Write("Lastly, what do you want to name your new dynamic method? ")
      Dim myMthdName As String = Console.ReadLine()
      
      ' Process inputNums into an array and create a corresponding Type array 
      Dim index As Integer = 0
      Dim inputNumsList As String() = inputNums.Split()
      
      Dim myMthdParams(inputNumsList.Length - 1) As Type
      Dim inputValsList(inputNumsList.Length - 1) As Object
      
      
      Dim inputNum As String
      For Each inputNum In  inputNumsList
         inputValsList(index) = CType(Convert.ToInt32(inputNum), Object)
         myMthdParams(index) = GetType(Integer)
         index += 1
      Next inputNum
      
      ' Now, call the method building method with the parameters, passing the 
      ' TypeBuilder by reference.
      AddMethodDynamically(myTypeBld, myMthdName, myMthdParams, GetType(Integer), myMthdAction)
      
      Dim myType As Type = myTypeBld.CreateType()
     
      Dim description as String 
      If myMthdAction = "A" Then
     description = "adding"
      Else
     description = "multiplying"
      End If

      Console.WriteLine("---")
      Console.WriteLine("The result of {0} the inputted values is: {1}", _
             description, _
                 myType.InvokeMember(myMthdName, _
                         BindingFlags.InvokeMethod Or _
                                 BindingFlags.Public Or _
                         BindingFlags.Static, _
                         Nothing, _
                         Nothing, _
                         inputValsList)) 
      Console.WriteLine("---")

      ' 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") 

      Dim myMthdInfo As MethodInfo = myType.GetMethod(myMthdName)
      Console.WriteLine("Your Dynamic Method: {0};", myMthdInfo.ToString())
   End Sub 'Main 
End Class 'DemoMethodBuilder


[C#] 

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


class DemoMethodBuilder {

    public static void AddMethodDynamically (ref 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 = Thread.GetDomain();
       AssemblyName asmName = new AssemblyName();
       asmName.Name = "DynamicAssembly1";
    
       AssemblyBuilder myAsmBuilder = myDomain.DefineDynamicAssembly(
                      asmName, 
                      AssemblyBuilderAccess.RunAndSave);

          ModuleBuilder myModule = myAsmBuilder.DefineDynamicModule("DynamicModule1",
                                        "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 or [M]ultiply these numbers? ");
       string myMthdAction = Console.ReadLine();
       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(ref myTypeBld,
                myMthdName,
                myMthdParams,
                typeof(int),    
                myMthdAction);

       Type myType = myTypeBld.CreateType();

       Console.WriteLine("---");
       Console.WriteLine("The result of {0} the inputted values is: {1}",
                 ((myMthdAction == "A") ? "adding" : "multiplying"),
                 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()); 
    
    }

}


[C++] 

#using <mscorlib.dll>

using namespace System;
using namespace System::Threading;
using namespace System::Reflection;
using namespace System::Reflection::Emit;


void AddMethodDynamically (TypeBuilder* myTypeBld,
                           String* mthdName,
                           Type* mthdParams[],
                           Type* returnType,
                           String* mthdAction)
{
   MethodBuilder*  myMthdBld = myTypeBld->DefineMethod(
      mthdName,
      static_cast<MethodAttributes>(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++) {
         if(mthdAction->Equals(S"A")) ILOut->Emit(OpCodes::Add);
         else if(mthdAction->Equals(S"M")) ILOut->Emit(OpCodes::Mul);
         else ILOut->Emit(OpCodes::Mul);
      }
   }
   ILOut->Emit(OpCodes::Ret);
}

int main() {

   AppDomain*  myDomain = Thread::GetDomain();
   AssemblyName* asmName = new AssemblyName();
   asmName->Name = S"DynamicAssembly1";

   AssemblyBuilder*  myAsmBuilder = myDomain->DefineDynamicAssembly(asmName,
      AssemblyBuilderAccess::RunAndSave);

   ModuleBuilder*  myModule = myAsmBuilder->DefineDynamicModule(S"DynamicModule1",
      S"MyDynamicAsm.dll");

   TypeBuilder*  myTypeBld = myModule->DefineType(S"MyDynamicType",
      TypeAttributes::Public);

   // Get info from the user to build the method dynamically.

   Console::WriteLine(S"Let's build a simple method dynamically!");
   Console::WriteLine(S"Please enter a few numbers, separated by spaces.");
   String* inputNums = Console::ReadLine();
   Console::Write(S"Do you want to [A]dd or [M]ultiply these numbers? ");
   String* myMthdAction = Console::ReadLine();
   Console::Write(S"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(0);

   Type* myMthdParams[] = new Type*[inputNumsList->Length];
   Object* inputValsList[] = new Object*[inputNumsList->Length];


   System::Collections::IEnumerator* myEnum = inputNumsList->GetEnumerator();
   while (myEnum->MoveNext()) {
      String* inputNum = __try_cast<String*>(myEnum->Current);

      inputValsList[index] = __box(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(S"---");
   Console::WriteLine(S"The result of {0} the inputted values is: {1}",
      ((myMthdAction->Equals(S"A")) ? S"adding" : S"multiplying"),
      myType->InvokeMember(myMthdName,static_cast<BindingFlags>(BindingFlags::InvokeMethod | BindingFlags::Public |
      BindingFlags::Static),
      0,
      0,
      inputValsList));
   Console::WriteLine(S"---");

   // 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(S"MyDynamicAsm.dll");

   MethodInfo*  myMthdInfo = myType->GetMethod(myMthdName);
   Console::WriteLine(S"Your Dynamic Method: {0};", myMthdInfo);
}

[JScript] No example is available for JScript. To view a Visual Basic, C#, or C++ example, click the Language Filter button Language Filter in the upper-left corner of the page.

Requirements

Namespace: System.Reflection.Emit

Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family

Assembly: Mscorlib (in Mscorlib.dll)

See Also

MethodBuilder Members | System.Reflection.Emit Namespace

Show:
© 2015 Microsoft