Dynamically Compose a Class in C#

c#, dynamic, reflection

Solution

I would consider using the C# Class compiler. From what I can remember you can build code that is in a string and you can get an assembly as output. This then enables you to invoke methods through reflection.

There is an example on the MSDN link I have specified but I will mock one up for here once I find my project.

Problem

Is it possible to dynamically compose a class from the methods contained in other Classes? For instance. Class A, B and C have public methods named such that they can be identified easily. They need to be extracted and added to Class D. Class D, which then contains all of the implementation logic can be passed further into a system which only accepts a single instance of Class D and dynamically binds these methods to other functions. To be clear, this is not inheritance I'm looking for. I'm literally stating that methods with different names need to be stuffed into one class. The system I pass it into understands these naming conventions and dynamically binds them (it's a black box to me). I am going down the path of extracting the methods from A, B, and C, dynamically combining them with the source of Class D in memory and compiling them into a new Class D and then creating an instance of D and passing it forward. ``` public class A{ public void EXPORT_A_DoSomething(){} } public class B{ public void EXPORT_B_DoSomethingElse(){}} public class C{ public void EXPORT_C_DoAnything(){}} //should become public class D{ public void EXPORT_A_DoSomething(){} public void EXPORT_B_DoSomethingElse(){} public void EXPORT_C_DoAnything(){} } ``` Is there a way to extract the MethodInfos from class A, B and C and somehow directly attach them to Class D? If so how?

Original source