Hello,
I need to extend a type at runtime in order to add some properties/fields to
it. I've managed to create the derived type with help from the
System.Reflection.Emit namespace and the code runs fine. Sample code:
namespace RefTest
{
public class Base
{
private string name = "name";
public string Name
{
get { return this.name; }
}
}
class Class1
{
[STAThread]
static void Main(string[] args)
{
Base o = (Base)CreateDerivedInstance();
Console.WriteLine("Name = " + o.Name);
}
public static object CreateDerivedInstance()
{
AssemblyName assemblyName = new AssemblyName();
assemblyName.Name = "MyDummyAssembly";
AppDomain domain = Thread.GetDomain();
AssemblyBuilder assemblyBuilder =
domain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave);
ModuleBuilder module =
assemblyBuilder.DefineDynamicModule("MyDummyModule", "MyModule.dll", true);
TypeBuilder typeBuilder = module.DefineType("Derived",
TypeAttributes.Public, typeof(Base));
ConstructorBuilder cb =
typeBuilder.DefineDefaultConstructor(MethodAttributes.Public);
// This type extends type Base
Type derived = typeBuilder.CreateType();
return Activator.CreateInstance(derived);
}
}
}
As you can see, in Main() I declare local variable 'o' of type Base but at
runtime it is actually an instance of type 'Derived'. The code runs fine. The
problem is that when I set a breakpoint and add 'o.Name' to the Watch window
I get "error: 'o.Name' does not exist" in the Value column. That is, I lose
debugging information about the variable even for members of the base class
(the 'Name' property).
Could anyone shed some light on this? Is there a workaround?
I'm using VS 2003.
Thanks in advance,
mayerber.
Yama - 28 Oct 2004 22:39 GMT
Hi Mayerber,
At what moment does o.Name break? hen you drag and drop the o object into
the Watch list, right after it is initialized, what do you see below? Does it
create a tree like of the object you can browse into?
Yama Kamyar
> Hello,
>
[quoted text clipped - 59 lines]
> Thanks in advance,
> mayerber.
mayerber - 30 Oct 2004 22:06 GMT
Hello Yama,
It breaks right away. When I drag and drop the 'o' variable to the Watch
window, I get "{}" for the Value column. It creates absolutely no tree to
browse. It's like the debugger completely loses all type information/symbols
about the object, including the symbols declared in the Base class (the Name
property, etc.).
Perhaps there's something that I must do in the CreateDerivedInstance()
method that helps the debugger with type information/symbols. I don't know...
Thanks for your interest,
mayerber.
> Hi Mayerber,
>
[quoted text clipped - 67 lines]
> > Thanks in advance,
> > mayerber.