tags:

views:

126

answers:

1

I have a typebuilder that is generating two identical .ctors one that is has no method body and the other that has all the init code.

I am defining a field from another type and a property to access the type and therefore need to init it in the .ctor

Where should I start looking

Code as follows

Public Sub ctor(ByVal type As TypeBuilder, ByVal FieldRefs As Dictionary(Of Type, FieldBuilder))
    ' Method attributes
    Dim methodAttributes As System.Reflection.MethodAttributes = MethodAttributes.[Public]

    Dim method As MethodBuilder = type.DefineMethod(".ctor", methodAttributes)
    ' Preparing Reflection instances

    Dim ctor1 As ConstructorInfo = GetType(Object).GetConstructor(BindingFlags.Instance Or BindingFlags.[Public] Or BindingFlags.NonPublic, Nothing, Nothing, Nothing)

    ' Setting return type
    method.SetReturnType(GetType(Void))
    ' Adding parameters
    Dim gen As ILGenerator = method.GetILGenerator()
    ' Writing body
    gen.Emit(OpCodes.Ldarg_0)
    gen.Emit(OpCodes.[Call], ctor1)

    'new up fields
    For Each item In FieldRefs
        AddCtor(type, gen, item.Value, item.Key)
    Next

    gen.Emit(OpCodes.Ret)

    ' finished
End Sub


Private Sub AddCtor(ByVal type As TypeBuilder, ByVal gen As ILGenerator, ByVal FieldBuilderRef As FieldBuilder, ByVal TypeToReference As Type)
    Dim TypeCtor = TypeToReference.GetConstructor(BindingFlags.Instance Or BindingFlags.[Public] Or BindingFlags.NonPublic, Nothing, New Type() {}, Nothing)
    gen.Emit(OpCodes.Ldarg_0)
    gen.Emit(OpCodes.Newobj, TypeCtor)
    gen.Emit(OpCodes.Stfld, FieldBuilderRef)
End Sub

Code takes in a dictionary of type , fieldbuilder to emit in the ctor. to new up the fields built earlier in the typebuilder main routine

+1  A: 

Are you sure one isn't the .cctor? But you are responsible for creating all constructors in a TypeBuilder; have you perhaps called DefineDefaultConstructor() in addition to DefineConstructor()? This would create an empty default constructor... so if you don't want an empty constructor, don't call this.

Marc Gravell