Assigning value to string from base type through constructor using TypeBuilder

127 views Asked by At

I am trying to programmatically define a class with a base class, and a constructor which calls the base constructor. Part of the subclass constructor's job is to initialize a string called name with a value. But no matter what I try name remains null. The base constructor works fine because some arraylists are initialized etc. Typesignature is a string. The field name already exists in the base class.

FieldBuilder fbname = tb.DefineField("name", typeof(string), FieldAttributes.Public);

ILGenerator ctor1IL = ctor1.GetILGenerator();
ctor1IL.Emit(OpCodes.Ldarg_0);

//get base constructor
var bc = tb.BaseType.GetConstructor(System.Type.EmptyTypes);
ctor1IL.Emit(OpCodes.Call, bc);  
ctor1IL.Emit(OpCodes.Ldarg_0);
ctor1IL.Emit(OpCodes.Ldstr, typeSignature);
ctor1IL.Emit(OpCodes.Stfld, fbname);
ctor1IL.Emit(OpCodes.Ret);
1

There are 1 answers

0
svick On BEST ANSWER

The field name already exists in the base class.

This sounds like you already have the field name in the base class. If that's the case, what your code does is to create another field called name in the derived class. You then write to that field, not to the one in the base class.

What you should do is something like:

FieldInfo nameField = tb.BaseType.GetField("name");

…

ctor1IL.Emit(OpCodes.Stfld, nameField);