Dynamic Typing – When and Why to Create Classes at Runtime?

cdynamic-typingpython

I have read many articles on the creation of dynamic types and classes at run time. For example, the TypeBuilder class in C# lets one create dynamic types. Python has this type function by which one can create dynamic classes. I have certainly good information on how I should create a class at run time, but I don't find enough information on why I should do this.

What is a scenario where one would be forced to create types at runtime?

Best Answer

Mock frameworks line NMock (for generating mock classes in unit test scenarios) do this.

Another application I can think of may be a generic database tool generating classes at run time for each table in the DB (of course, there may be better solutions for this purpose).

In C#, every time when you have the requirement to construct a function at runtime (because, for example, the user is able to enter a function defined by himself in your application), you will need a dynamic class for that purpose since in C# functions cannot live "on their own".

And another application I know of are the dynamically created COM wrappers in C#4.0 for every COM component. Up to C# 3.5, you needed first to generate some type library wrapper which had to be compiled first before you could use it. With C#4.0 and the dynamic keyword, this is not necessary any more, the wrapper can be constructed at run time by the framework and you can write code which calls methods of those classes.