Dynamically create a c# generic type with self referenced constraints

Go To StackoverFlow.com

4

I have a generic type that look like this

public class Entity<T> where T : Entity<T>{ ... }

and I need to dynamically construct the type T. So that it looks like this:

public class MyClass : Entity<MyClass>{ ... }

Can this be done ?

2012-04-04 23:50
by Rushui Guan
Was the reuse of "T" on purpose? Would "public class MyClass : Entity{}" be the same - Joe Enzminger 2012-04-04 23:54
No, MyClass would have been a better name - Rushui Guan 2012-04-05 00:45
What would the value be in "dynamically constructing" such a derived type over simply defining it directly:

public class MyEntity : Entity { - David Nelson 2012-04-05 03:32

I am working on data binding of "Entity" objects. The property descriptors of the "Entity" object depends on its factory class. But when using a custom TypeDescriptionProvider, the property descriptors are returned based on Type. Therefore I have no choice but to dynamically create wrapper types and associate it with its instance of factory - Rushui Guan 2012-04-05 04:13


5

AssemblyName assemblyName = new AssemblyName("TestAssembly");
AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);

ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName.Name);

TypeBuilder typeBuilder = moduleBuilder.DefineType("MyClass", TypeAttributes.Public);

Type entityType = typeof(Entity<>).MakeGenericType(typeBuilder);

typeBuilder.SetParent(entityType);


Type t = typeBuilder.CreateType();
2012-04-05 00:11
by Joe Enzminger
Code snippet above assumes the class Entity is already defined - Joe Enzminger 2012-04-05 00:13
Thanks! That's exactly what I am looking for - Rushui Guan 2012-04-05 00:44
I didn't know TypeBuilder itself is actually a Type too - Rushui Guan 2012-04-05 13:42
Ads