How can I add a member field to an existing class in runtime?

  • Thread starter Thread starter Mannie
  • Start date Start date
M

Mannie

Is there any way I can add a member field to an already existing class
during runtime?

I know there are many examples using Reflection.Emit showing how to
dynamically create a new class and adding things to it, but that's not what
I want. I really need to use existing classes. I have investigated the
Profiler API, but having its dll snapped to the CLR reminds me of the Borg
and their implants. It is not really what I -or my customers- want for
production.

I need this because I'm creating a simple OO database which needs references
to objects when updating. The value that I want to add on the fly is the
object id.

Thanks!
Manfred Suttorp

PS. I would appreciate relevant comments only - no lectures about OO design
or telling me I shouldn't do this please.
 
You could very easily use any of the major AOP frameworks for .NET to
implement this as a "mixin" .. aspect#, naspect, and many others support
this type of behavior out of the box.

Or if you don't like that idea .. you could do the same thing they do .. on
your own without the overhead of the additional functionality

say I have the following class ..

public class Foo {
public int Bar;
public void Foo() { }
}

dynamically generate a class that looks like the following.

public class AddedId : Foo {
public long objectid;
}

If you are creating objects through a factory .. this is quite simple .. if
you are not you may have to get into situations where you use reflections to
copy over data from an existant foo into your class.

Cheers,

Greg Young
 
Back
Top