RE: Extending a type at runtime - debugging issue

Tech Tip: Click here to run a free scan for Windows Errors and optimize PC performance

From: Yama (Yama_at_discussions.microsoft.com)
Date: 10/28/04


Date: Thu, 28 Oct 2004 14:39:07 -0700

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

"mayerber" wrote:

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