This documentation is archived and is not being maintained.

TypeBuilder Class

Defines and creates new instances of classes during run time.

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

'Declaration
<ClassInterfaceAttribute(ClassInterfaceType.None)> _
<ComVisibleAttribute(True)> _
<HostProtectionAttribute(SecurityAction.LinkDemand, MayLeakOnAbort := True)> _
Public NotInheritable Class TypeBuilder _
	Inherits Type _
	Implements _TypeBuilder
'Usage
Dim instance As TypeBuilder

NoteNote:

The HostProtectionAttribute attribute applied to this type or member has the following Resources property value: MayLeakOnAbort. The HostProtectionAttribute does not affect desktop applications (which are typically started by double-clicking an icon, typing a command, or entering a URL in a browser). For more information, see the HostProtectionAttribute class or SQL Server Programming and Host Protection Attributes.

TypeBuilder is the root class used to control the creation of dynamic classes in the runtime. TypeBuilder provides a set of routines that are used to define classes, add methods and fields, and create the class inside the runtime. A new TypeBuilder can be created from a dynamic module.

To create an array type, pointer type, or byref type for an incomplete type that is represented by a TypeBuilder object, use the MakeArrayType method, MakePointerType method, or MakeByRefType method, respectively.

This section contains two code examples. The first example shows how to create a dynamic type with a field, constructor, property, and method. The second example builds a method dynamically from user input.

Example one

The following code example shows how to define a dynamic assembly with one module. The module in the example assembly contains one type, MyDynamicType, which has a private field, a property that gets and sets the private field, constructors that initialize the private field, and a method that multiplies a user-supplied number by the private field value and returns the result.

The AssemblyBuilderAccess.RunAndSave field is specified when the assembly is created. The assembly code is used immediately, and the assembly is also saved to disk so that it can be examined with MSIL Disassembler (Ildasm.exe) or used in another program.

Imports System
Imports System.Reflection
Imports System.Reflection.Emit

Class DemoAssemblyBuilder

    Public Shared Sub Main()

        ' An assembly consists of one or more modules, each of which 
        ' contains zero or more types. This code creates a single-module 
        ' assembly, the most common case. The module contains one type, 
        ' named "MyDynamicType", that has a private field, a property  
        ' that gets and sets the private field, constructors that  
        ' initialize the private field, and a method that multiplies 
        ' a user-supplied number by the private field value and returns  
        ' the result. The code might look like this in Visual Basic: 
        
        'Public Class MyDynamicType 
        '    Private m_number As Integer 
        
        '    Public Sub New() 
        '        Me.New(42) 
        '    End Sub 
        
        '    Public Sub New(ByVal initNumber As Integer) 
        '        m_number = initNumber 
        '    End Sub 
        
        '    Public Property Number As Integer 
        '        Get 
        '            Return m_number 
        '        End Get 
        '        Set 
        '            m_Number = Value 
        '        End Set 
        '    End Property 
        
        '    Public Function MyMethod(ByVal multiplier As Integer) As Integer 
        '        Return m_Number * multiplier 
        '    End Function 
        'End Class 

        Dim aName As New AssemblyName("DynamicAssemblyExample")
        Dim ab As AssemblyBuilder = _
            AppDomain.CurrentDomain.DefineDynamicAssembly( _
                aName, _
                AssemblyBuilderAccess.RunAndSave)

        ' For a single-module assembly, the module name is usually 
        ' the assembly name plus an extension. 
        Dim mb As ModuleBuilder = ab.DefineDynamicModule( _
            aName.Name, _
            aName.Name & ".dll")

        Dim tb As TypeBuilder = _
            mb.DefineType("MyDynamicType", TypeAttributes.Public)

        ' Add a private field of type Integer (Int32). 
        Dim fbNumber As FieldBuilder = tb.DefineField( _
            "m_number", _
            GetType(Integer), _
            FieldAttributes.Private)

        ' Define a constructor that takes an integer argument and  
        ' stores it in the private field.  
        Dim parameterTypes() As Type = { GetType(Integer) }
        Dim ctor1 As ConstructorBuilder = _
            tb.DefineConstructor( _
                MethodAttributes.Public, _
                CallingConventions.Standard, _
                parameterTypes)

        Dim ctor1IL As ILGenerator = ctor1.GetILGenerator()
        ' For a constructor, argument zero is a reference to the new 
        ' instance. Push it on the stack before calling the base 
        ' class constructor. Specify the default constructor of the  
        ' base class (System.Object) by passing an empty array of  
        ' types (Type.EmptyTypes) to GetConstructor.
        ctor1IL.Emit(OpCodes.Ldarg_0)
        ctor1IL.Emit(OpCodes.Call, _
            GetType(Object).GetConstructor(Type.EmptyTypes))
        ' Push the instance on the stack before pushing the argument 
        ' that is to be assigned to the private field m_number.
        ctor1IL.Emit(OpCodes.Ldarg_0)
        ctor1IL.Emit(OpCodes.Ldarg_1)
        ctor1IL.Emit(OpCodes.Stfld, fbNumber)
        ctor1IL.Emit(OpCodes.Ret)

        ' Define a default constructor that supplies a default value 
        ' for the private field. For parameter types, pass the empty 
        ' array of types or pass Nothing. 
        Dim ctor0 As ConstructorBuilder = tb.DefineConstructor( _
            MethodAttributes.Public, _
            CallingConventions.Standard, _
            Type.EmptyTypes)

        Dim ctor0IL As ILGenerator = ctor0.GetILGenerator()
        ' For a constructor, argument zero is a reference to the new 
        ' instance. Push it on the stack before pushing the default 
        ' value on the stack, then call constructor ctor1.
        ctor0IL.Emit(OpCodes.Ldarg_0)
        ctor0IL.Emit(OpCodes.Ldc_I4_S, 42)
        ctor0IL.Emit(OpCodes.Call, ctor1)
        ctor0IL.Emit(OpCodes.Ret)

        ' Define a property named Number that gets and sets the private  
        ' field. 
        
        ' The last argument of DefineProperty is Nothing, because the 
        ' property has no parameters. (If you don't specify Nothing, you must 
        ' specify an array of Type objects. For a parameterless property, 
        ' use the built-in array with no elements: Type.EmptyTypes) 
        Dim pbNumber As PropertyBuilder = tb.DefineProperty( _
            "Number", _
            PropertyAttributes.HasDefault, _
            GetType(Integer), _
            Nothing)

        ' The property Set and property Get methods require a special 
        ' set of attributes. 
        Dim getSetAttr As MethodAttributes = _
            MethodAttributes.Public Or MethodAttributes.SpecialName _
                Or MethodAttributes.HideBySig

        ' Define the "get" accessor method for Number. The method returns 
        ' an integer and has no arguments. (Note that Nothing could be  
        ' used instead of Types.EmptyTypes) 
        Dim mbNumberGetAccessor As MethodBuilder = tb.DefineMethod( _
            "get_Number", _
            getSetAttr, _
            GetType(Integer), _
            Type.EmptyTypes)

        Dim numberGetIL As ILGenerator = mbNumberGetAccessor.GetILGenerator()
        ' For an instance property, argument zero is the instance. Load the  
        ' instance, then load the private field and return, leaving the 
        ' field value on the stack.
        numberGetIL.Emit(OpCodes.Ldarg_0)
        numberGetIL.Emit(OpCodes.Ldfld, fbNumber)
        numberGetIL.Emit(OpCodes.Ret)

        ' Define the "set" accessor method for Number, which has no return 
        ' type and takes one argument of type Integer (Int32). 
        Dim mbNumberSetAccessor As MethodBuilder = _
            tb.DefineMethod( _
                "set_Number", _
                getSetAttr, _
                Nothing, _
                New Type() { GetType(Integer) })

        Dim numberSetIL As ILGenerator = mbNumberSetAccessor.GetILGenerator()
        ' Load the instance and then the numeric argument, then store the 
        ' argument in the field.
        numberSetIL.Emit(OpCodes.Ldarg_0)
        numberSetIL.Emit(OpCodes.Ldarg_1)
        numberSetIL.Emit(OpCodes.Stfld, fbNumber)
        numberSetIL.Emit(OpCodes.Ret)

        ' Last, map the "get" and "set" accessor methods to the  
        ' PropertyBuilder. The property is now complete. 
        pbNumber.SetGetMethod(mbNumberGetAccessor)
        pbNumber.SetSetMethod(mbNumberSetAccessor)

        ' Define a method that accepts an integer argument and returns 
        ' the product of that integer and the private field m_number. This 
        ' time, the array of parameter types is created on the fly. 
        Dim meth As MethodBuilder = tb.DefineMethod( _
            "MyMethod", _
            MethodAttributes.Public, _
            GetType(Integer), _
            New Type() { GetType(Integer) })

        Dim methIL As ILGenerator = meth.GetILGenerator()
        ' To retrieve the private instance field, load the instance it 
        ' belongs to (argument zero). After loading the field, load the  
        ' argument one and then multiply. Return from the method with  
        ' the return value (the product of the two numbers) on the  
        ' execution stack.
        methIL.Emit(OpCodes.Ldarg_0)
        methIL.Emit(OpCodes.Ldfld, fbNumber)
        methIL.Emit(OpCodes.Ldarg_1)
        methIL.Emit(OpCodes.Mul)
        methIL.Emit(OpCodes.Ret)

        ' Finish the type. 
        Dim t As Type = tb.CreateType()

        ' The following line saves the single-module assembly. This 
        ' requires AssemblyBuilderAccess to include Save. You can now 
        ' type "ildasm MyDynamicAsm.dll" at the command prompt, and  
        ' examine the assembly. You can also write a program that has 
        ' a reference to the assembly, and use the MyDynamicType type. 
        ' 
        ab.Save(aName.Name & ".dll") 

        ' Because AssemblyBuilderAccess includes Run, the code can be 
        ' executed immediately. Start by getting reflection objects for 
        ' the method and the property. 
        Dim mi As MethodInfo = t.GetMethod("MyMethod")
        Dim pi As PropertyInfo = t.GetProperty("Number")

        ' Create an instance of MyDynamicType using the default  
        ' constructor.  
        Dim o1 As Object = Activator.CreateInstance(t)

        ' Display the value of the property, then change it to 127 and  
        ' display it again. Use Nothing to indicate that the property 
        ' has no index.
        Console.WriteLine("o1.Number: {0}", pi.GetValue(o1, Nothing))
        pi.SetValue(o1, 127, Nothing)
        Console.WriteLine("o1.Number: {0}", pi.GetValue(o1, Nothing))

        ' Call MyMethod, passing 22, and display the return value, 22 
        ' times 127. Arguments must be passed as an array, even when 
        ' there is only one. 
        Dim arguments() As Object = { 22 }
        Console.WriteLine("o1.MyMethod(22): {0}", _
            mi.Invoke(o1, arguments))

        ' Create an instance of MyDynamicType using the constructor 
        ' that specifies m_Number. The constructor is identified by 
        ' matching the types in the argument array. In this case,  
        ' the argument array is created on the fly. Display the  
        ' property value. 
        Dim o2 As Object = Activator.CreateInstance(t, _
            New Object() { 5280 })
        Console.WriteLine("o2.Number: {0}", pi.GetValue(o2, Nothing))

    End Sub   
End Class 

' This code produces the following output: 

'o1.Number: 42 
'o1.Number: 127 
'o1.MyMethod(22): 2794 
'o2.Number: 5280

Example two

The following code sample demonstrates how to build a dynamic type by using TypeBuilder.

Imports System
Imports System.Threading
Imports System.Reflection
Imports System.Reflection.Emit

 _


Class TestILGenerator


   Public Shared Function DynamicDotProductGen() As Type

      Dim ivType As Type = Nothing 
      Dim ctorParams() As Type = {GetType(Integer), GetType(Integer), GetType(Integer)}

      Dim myDomain As AppDomain = Thread.GetDomain()
      Dim myAsmName As New AssemblyName()
      myAsmName.Name = "IntVectorAsm" 

      Dim myAsmBuilder As AssemblyBuilder = myDomain.DefineDynamicAssembly( _
					    myAsmName, _
					    AssemblyBuilderAccess.RunAndSave)

      Dim IntVectorModule As ModuleBuilder = myAsmBuilder.DefineDynamicModule( _
					     "IntVectorModule", _
					     "Vector.dll")

      Dim ivTypeBld As TypeBuilder = IntVectorModule.DefineType("IntVector", TypeAttributes.Public)

      Dim xField As FieldBuilder = ivTypeBld.DefineField("x", _
						         GetType(Integer), _
						         FieldAttributes.Private)
      Dim yField As FieldBuilder = ivTypeBld.DefineField("y", _ 
						         GetType(Integer), _
						         FieldAttributes.Private)
      Dim zField As FieldBuilder = ivTypeBld.DefineField("z", _
						         GetType(Integer), _
						         FieldAttributes.Private)


      Dim objType As Type = Type.GetType("System.Object")
      Dim objCtor As ConstructorInfo = objType.GetConstructor(New Type() {})

      Dim ivCtor As ConstructorBuilder = ivTypeBld.DefineConstructor( _
					 MethodAttributes.Public, _
					 CallingConventions.Standard, _
					 ctorParams)
      Dim ctorIL As ILGenerator = ivCtor.GetILGenerator()
      ctorIL.Emit(OpCodes.Ldarg_0)
      ctorIL.Emit(OpCodes.Call, objCtor)
      ctorIL.Emit(OpCodes.Ldarg_0)
      ctorIL.Emit(OpCodes.Ldarg_1)
      ctorIL.Emit(OpCodes.Stfld, xField)
      ctorIL.Emit(OpCodes.Ldarg_0)
      ctorIL.Emit(OpCodes.Ldarg_2)
      ctorIL.Emit(OpCodes.Stfld, yField)
      ctorIL.Emit(OpCodes.Ldarg_0)
      ctorIL.Emit(OpCodes.Ldarg_3)
      ctorIL.Emit(OpCodes.Stfld, zField)
      ctorIL.Emit(OpCodes.Ret)


      ' Now, you'll construct the method find the dot product of two vectors. First, 
      ' let's define the parameters that will be accepted by the method. In this case, 
      ' it's an IntVector itself! 

      Dim dpParams() As Type = {ivTypeBld}

      ' Here, you create a MethodBuilder containing the 
      ' name, the attributes (public, static, private, and so on), 
      ' the return type (int, in this case), and a array of Type 
      ' indicating the type of each parameter. Since the sole parameter 
      ' is a IntVector, the very class you're creating, you will 
      ' pass in the TypeBuilder (which is derived from Type) instead of  
      ' a Type object for IntVector, avoiding an exception.  
      ' -- This method would be declared in VB.NET as: 
      '    Public Function DotProduct(IntVector aVector) As Integer 

      Dim dotProductMthd As MethodBuilder = ivTypeBld.DefineMethod("DotProduct", _
					    MethodAttributes.Public, GetType(Integer), _
                                            dpParams)

      ' A ILGenerator can now be spawned, attached to the MethodBuilder. 
      Dim mthdIL As ILGenerator = dotProductMthd.GetILGenerator()

      ' Here's the body of our function, in MSIL form. We're going to find the 
      ' "dot product" of the current vector instance with the passed vector  
      ' instance. For reference purposes, the equation is: 
      ' (x1 * x2) + (y1 * y2) + (z1 * z2) = the dot product 
      ' First, you'll load the reference to the current instance "this" 
      ' stored in argument 0 (ldarg.0) onto the stack. Ldfld, the subsequent 
      ' instruction, will pop the reference off the stack and look up the 
      ' field "x", specified by the FieldInfo token "xField".
      mthdIL.Emit(OpCodes.Ldarg_0)
      mthdIL.Emit(OpCodes.Ldfld, xField)

      ' That completed, the value stored at field "x" is now atop the stack. 
      ' Now, you'll do the same for the object reference we passed as a 
      ' parameter, stored in argument 1 (ldarg.1). After Ldfld executed, 
      ' you'll have the value stored in field "x" for the passed instance 
      ' atop the stack.
      mthdIL.Emit(OpCodes.Ldarg_1)
      mthdIL.Emit(OpCodes.Ldfld, xField)

      ' There will now be two values atop the stack - the "x" value for the 
      ' current vector instance, and the "x" value for the passed instance. 
      ' You'll now multiply them, and push the result onto the evaluation stack.
      mthdIL.Emit(OpCodes.Mul_Ovf_Un)

      ' Now, repeat this for the "y" fields of both vectors.
      mthdIL.Emit(OpCodes.Ldarg_0)
      mthdIL.Emit(OpCodes.Ldfld, yField)
      mthdIL.Emit(OpCodes.Ldarg_1)
      mthdIL.Emit(OpCodes.Ldfld, yField)
      mthdIL.Emit(OpCodes.Mul_Ovf_Un)

      ' At this time, the results of both multiplications should be atop 
      ' the stack. You'll now add them and push the result onto the stack.
      mthdIL.Emit(OpCodes.Add_Ovf_Un)

      ' Multiply both "z" field and push the result onto the stack.
      mthdIL.Emit(OpCodes.Ldarg_0)
      mthdIL.Emit(OpCodes.Ldfld, zField)
      mthdIL.Emit(OpCodes.Ldarg_1)
      mthdIL.Emit(OpCodes.Ldfld, zField)
      mthdIL.Emit(OpCodes.Mul_Ovf_Un)

      ' Finally, add the result of multiplying the "z" fields with the 
      ' result of the earlier addition, and push the result - the dot product - 
      ' onto the stack.
      mthdIL.Emit(OpCodes.Add_Ovf_Un)

      ' The "ret" opcode will pop the last value from the stack and return it 
      ' to the calling method. You're all done!
      mthdIL.Emit(OpCodes.Ret)


      ivType = ivTypeBld.CreateType()

      Return ivType
   End Function 'DynamicDotProductGen


   Public Shared Sub Main()

      Dim IVType As Type = Nothing 
      Dim aVector1 As Object = Nothing 
      Dim aVector2 As Object = Nothing 
      Dim aVtypes() As Type = {GetType(Integer), GetType(Integer), GetType(Integer)}
      Dim aVargs1() As Object = {10, 10, 10}
      Dim aVargs2() As Object = {20, 20, 20}

      ' Call the  method to build our dynamic class.
      IVType = DynamicDotProductGen()


      Dim myDTctor As ConstructorInfo = IVType.GetConstructor(aVtypes)
      aVector1 = myDTctor.Invoke(aVargs1)
      aVector2 = myDTctor.Invoke(aVargs2)

      Console.WriteLine("---")
      Dim passMe(0) As Object
      passMe(0) = CType(aVector2, Object)

      Console.WriteLine("(10, 10, 10) . (20, 20, 20) = {0}", _
                        IVType.InvokeMember("DotProduct", BindingFlags.InvokeMethod, _
                        Nothing, aVector1, passMe))
   End Sub 'Main
End Class 'TestILGenerator



' +++ OUTPUT +++ 
' --- 
' (10, 10, 10) . (20, 20, 20) = 600 

System.Object
  System.Reflection.MemberInfo
    System.Type
      System.Reflection.Emit.TypeBuilder

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

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

.NET Framework

Supported in: 3.5, 3.0, 2.0, 1.1, 1.0
Show: