[Mono-devel-list] Dynamically changing classes?

Jonathan Pryor jonpryor at vt.edu
Wed Sep 24 18:11:29 EDT 2003

Response inline...

On Wed, 2003-09-24 at 14:12, Thomas Sondergaard wrote:
> Can a .net class be changed at runtime? Can you add/remove methods and
> fields at runtime?


> If one were to compile a dynamically typed language like Ruby or Python to
> IL and the classes were to be directly represented by .net classes and not
> .net objects this would be necessary.
> I have been using the emit API but this just adds a new assembly either to
> memory or a file, so I don't see how I can use it to dynamically change
> existing types.

Well...  You be cute about it. :-)

For every change (added method, field) to a class, you actually create a
new derived object.  You determine the actual object to instantiate by
keeping the most-derived class name hanging around a well-known

	class RuntimeInfo {
		public static string ActualClassName = "Something_2"

	// at runtime...
	class Something_0 { ... }
	class Something_1 : Something_0 {...}
	class Something_2 : Something_1 {...}

Problem: it doesn't handle updating existing class instances.  Thus,
this may be unsuitable for some situations.

> In CIL you can call a virtual function. This, as far as I understand, is the
> limit to late binding as implemented in .net (without reflection). In ruby
> and Python the concept of sending messages to an object is more dynamic and
> has nothing to do with types. Using Type.InvokeMember you can mimic this
> behaviour on .net but could it is relatively slow. Why not add a new
> instruction to the CLR that is simply called e.g. 'send_msg'  that accepts a
> methodName string and a list of parameters? This would be essential for
> dynamically typed languages wouldn't it.

Why add a new CIL instruction, when you can just do it yourself?

	interface IDynamicLanguage {
		public object Invoke (string message, object[] args);

Just have all your internal classes implement IDynamicLanguage, and you
get the same functionality as "send_msg".  There's no particular reason
why this has to be in CIL, as opposed to doing it yourself (above).

> Disclaimer: I don't really know much about this I'm just wondering what kind
> of platform support that is necessary if you want dynamically typed
> languages to execute more or less directly on the CLR, meaning that classes
> are represented by .net classes and not .net objects.

This is an open research question. :-)

The ways outlined above would work, but they're not necessarily the
*best* way to do it.  I'm not sure what the best way is, and I'm not
sure anyone else knows either, for that matter.

Thus, research and experimentation are required. :-)

 - Jon

More information about the Mono-devel-list mailing list