Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using extension methods with runtime assemblies

Is there any way to use extension methods on a class that has been dynamically created using Relection.Emit? For example:

 class somewhere
 {
     somewhere()
     {
         // define the type here using ReflectionEmit, etc.
         Type tableType = CreateTableType(...table parameters...);

         var table = Activator.CreateInstance(tableType);
         table.Shuffle();
     } 
 }

 //... elsewhere
 public class static TableTypeExtensions   
 {
      public static Table Shuffle( this Table t)  
      {   
          ...
      }
 }

But I don't have the class by name "Table", only Type tableType available.
Is there any way around this?
Thanks

like image 721
Max Yaffe Avatar asked May 30 '26 10:05

Max Yaffe


2 Answers

Make the dynamic class implement an interface (an empty one if you want), add extensions to the interface.

like image 178
µBio Avatar answered Jun 01 '26 02:06

µBio


Define a common base class for your TableType and define the extension method on that. This way your extension method should be available for the derived classes as well.

like image 20
Rune Grimstad Avatar answered Jun 01 '26 02:06

Rune Grimstad



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!