Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically overriding an abstract method in c#

Tags:

c#

I have the following abstract class which CAN NOT be changed.

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?

like image 316
ng. Avatar asked Jan 20 '26 01:01

ng.


1 Answers

You have the wrong return type on the dynamically created function. It should be string instead of void:

typeBuilder.DefineMethod("GetName",   
MethodAttributes.Public | 
MethodAttributes.ReuseSlot |
MethodAttributes.Virtual | 
MethodAttributes.HideBySig,
typeof(string),
Type.EmptyTypes);
like image 195
Pent Ploompuu Avatar answered Jan 21 '26 13:01

Pent Ploompuu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!