Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to build a new type during Runtime?

Tags:

I am going to ask a question that might sound weird.

Is there a way to build a new class during Runtime? Or at least, add a new property to an existing class.

I mean creating a class that doesn't exist and not an instance of an existing class. I could later on use reflections to load and use this class.

like image 265
user88637 Avatar asked May 30 '09 08:05

user88637


People also ask

Can we create a class at runtime?

Dynamic Class creation enables you to create a Java class on the fly at runtime, from source code created from a string. Dynamic class creation can be used in extremely low latency applications to improve performance.

Can we create a class dynamically in C#?

You can create custom dynamic objects by using the classes in the System. Dynamic namespace. For example, you can create an ExpandoObject and specify the members of that object at run time. You can also create your own type that inherits the DynamicObject class.


2 Answers

Adding a property to an existing type is not possible, but you can create a new type at runtime using Reflection.Emit. It's pretty complicated stuff, and it goes something like this:

AssemblyBuilder assemblyBuilder = Thread.GetDomain().DefineDynamicAssembly(       assemblyName , AssemblyBuilderAccess.Run, assemblyAttributes); ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("ModuleName"); TypeBuilder typeBuilder = moduleBuilder.DefineType(       "MyNamespace.TypeName" , TypeAttributes.Public);  typeBuilder.DefineDefaultConstructor(MethodAttributes.Public);  // Add a method newMethod = typeBuilder.DefineMethod("MethodName" , MethodAttributes.Public);  ILGenerator ilGen = newMethod.GetILGenerator();  // Create IL code for the method ilGen.Emit(...);  // ...  // Create the type itself Type newType = typeBuilder.CreateType(); 

This code is just a sample. It could contain errors.

You can also generate classes by compiling C# source code at runtime using System.CodeDom, but I don't know a lot about that.

like image 191
Philippe Leybaert Avatar answered Oct 05 '22 12:10

Philippe Leybaert


Take a look at the System.Reflection.Emit namespace. I've never used it myself but the classes in this namespace can be used to generate IL (intermediate language).

like image 28
Ronald Wildenberg Avatar answered Oct 05 '22 13:10

Ronald Wildenberg