Dynamically overriding an abstract method in c#

Posted by ng on Stack Overflow See other posts from Stack Overflow or by ng
Published on 2010-05-13T10:50:49Z Indexed on 2010/05/13 10:54 UTC
Read the original article Hit count: 292

Filed under:

I have the following abstract class

public abstract class AbstractThing {
   public String GetDescription() {
      return "This is " + GetName();
   }
   public abstract String GetName();
}

Now I would like to implement some new dynamic types from this like so.

AssemblyName assemblyName = new AssemblyName();
assemblyName.Name = "My.TempAssembly";
AssemblyBuilder assemblyBuilder = Thread.GetDomain().DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
ModuleBuilder moduleBuilder =  assemblyBuilder.DefineDynamicModule("DynamicThings");
TypeBuilder typeBuilder = moduleBuilder.DefineType(someName + "_Thing", 
                TypeAttributes.Public | 
                TypeAttributes.Class, 
                 typeof(AbstractThing));
MethodBuilder methodBuilder = typeBuilder.DefineMethod("GetName",    
                MethodAttributes.Public | 
                MethodAttributes.ReuseSlot |
                MethodAttributes.Virtual | 
                MethodAttributes.HideBySig,
                null,
                Type.EmptyTypes);

ILGenerator msil = methodBuilder.GetILGenerator();

msil.EmitWriteLine(selectionList);
msil.Emit(OpCodes.Ret);

However when I try to instantiate via

typeBuilder.CreateType();

I get an exception saying that there is no implementation for GetName. Is there something I am doing wrong here. I can not see the problem.

Also, what would be the restrictions on instantiating such a class by name? For instance if I tried to instantiate via "My.TempAssembly.x_Thing" would it be availble for instantiation without the Type generated?

© Stack Overflow or respective owner

Related posts about c#