Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi I googled but couldn't find a good answer, heres my question;
Is it possible to derive classses in runtime?
Posted

1 solution

There is one way: you can create an assembly during run time, using System.Reflection.Emit, and, in this assembly, create a type with required features (it could be a class derived from some existing type) and later use it using System.Reflection — in in the same runtime. Please see:
http://msdn.microsoft.com/en-us/library/system.reflection.emit.aspx[^],
http://msdn.microsoft.com/en-us/library/3y322t50.aspx[^].

This is an interesting simple introductory article: http://www.drdobbs.com/generating-code-at-run-time-with-reflect/184416570[^].

This is one CodeProject article, more in depth:
Introduction to Creating Dynamic Types with Reflection.Emit[^],
Introduction to Creating Dynamic Types with Reflection.Emit: Part 2[^].

A good CodeProject article:
Dynamic Type Using Reflection.Emit[^].

I generally recommend to look at CodeProject articles on the topic; some are very interesting:
http://www.codeproject.com/search.aspx?doctypeid=1&q=Reflection.emit[^].

I must add that creating code using System.Reflection.Emit is a very important feature to be used in some scenarios. For example, it is used in serialization, for getting good performance of the code generated from metadata. This CodeProject article shows another important application of it:
Using Reflection.Emit to Precompile Expressions to MSIL[^].

It requires good knowledge if MSIL. The work is tedious enough and the code is really hard to debug. The code in C# being debugged only shows you the process of code generation, but not generated code. So, you should only use it when you want to get some miraculous and very fundamental universal results. This is not a work for your everyday programming.

—SA
 
Share this answer
 
v2
Comments
Espen Harlinn 4-Nov-12 11:36am    
5'ed!
Sergey Alexandrovich Kryukov 4-Nov-12 11:50am    
Thank you, Espen.
--SA
Maciej Los 4-Nov-12 13:15pm    
What can i say? GREAT, +5!
Sergey Alexandrovich Kryukov 4-Nov-12 13:46pm    
Thank you, Maciej.
--SA
tasinsahin 4-Nov-12 17:01pm    
thank you Sergey! Now, i m studying your links :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900