0

I would like to override a virtual base class function on the fly and use this overriden method in application. If I write a basic example class:

partial Class myBase
{
   public myBase() {}
   public virtual void DoStuff()
   {
      throw new Exception("this function is not overriden");
   }
}

partial Class myDeriv : myBase
{
   public myDeriv() {}
}

And now I would like to override myDeriv.DoStuff on the fly. So I create a string code block and compile it using

CSharpCodeProvider.CompileAssemblyFromSource

method. After writing this dll to disk I tried to load it using

Assembly.LoadFrom("onTheFly.dll");

But application fails to find this overridden function. If you have any other better solutions I'm open to them also.. I just need to override functions on the fly..

Thank you all!

MCA
  • 59
  • 5
  • we need some more info: in which assemblies are these classes and we need to see the code where you override those classes – hcb Jul 18 '11 at 10:27
  • Not very sure if you can override virtual function on the fly. But may be you can use "new" keyword to "override" your NON virtual function ? – Tigran Jul 18 '11 at 10:28
  • @hcb I have written the assembly which includes the base and derived class (I corrected example code these classes are partial). And I would like to create on the fly assembly or create, compile new overriding method and attach to this derived class. – MCA Jul 18 '11 at 10:33
  • @Tigran can I create a new function and/or override the old one? – MCA Jul 18 '11 at 10:33
  • that's what I mean, I'm not very sure if yuo can override at runtime virtual method, as virtual table content have to be rebuild, basically, but you can try to use "new" keyword. – Tigran Jul 18 '11 at 11:56
  • @MCA Are you dynamically creating (and emitting and loading) a new subclass? And how are you attempting to execute the new code after loading it using `Assembly.LoadFrom(string)`? – Thomas Gerstendörfer Jul 18 '11 at 12:08

1 Answers1

1

I think it is not possible seems to be be caused by the same rule as described here or here

Quote from the original:

"You cannot have two partial classes referring to the same class in two different assemblies (projects). Once the assembly is compiled, the meta-data is baked in, and your classes are no longer partial. Partial classes allows you to split the definition of the same class into two files."

or

"You cannot use the partial keyword to split the code for a class between projects. The partial keyword is a compiler trick; the compiler will output one single class out of the parts it finds, so all parts of the class must exist with the same binary file. Once the class is compiled, there is no trace left of it being a partial class.

If you want to extend an existing class you will either need to inherit it (if it is not sealed), or create your own new class that contains the classes that you wish to combine information from."

Community
  • 1
  • 1
Bogdan
  • 1,323
  • 15
  • 15