Thanks for your reply Göran.
Whilst I do agree that one should obey the fundamental principles of OOP, I
want the trick in this case anyway.
Deriving from existing classes is simply not acceptable here: what if some
sealed class must be persisted in my OO database? I would have to resort to
a wrapper class. It creates horrible code.
Also, the name of <ExistingClass> is not known to my OO database in advance,
so any code using the database must use a wrapper (be it a derived class or
a container, it's the same in this case) for every possible Type that I wish
to persist. I simply don't want that. The nitty-gritty details of the
persistence mechanism should be irrelevant to the consuming code and so it
should not be bothered with things like its object id if it's not essential
to its reason of existence. Also, one could argue that subclassing for the
sake of facilitating some low-level technical requirement, having nothing to
do with specialization is not very good OO practice either.
More suggestions are very welcome. One other thing though - and no offence
meant to Göran - I've seen a lot of good and bad practices, patterns and
antipatterns in my career. I'm not really interested in more lectures about
them. All I want is a good answer to my question.
Regards,
Manfred
[quoted text, click to view] "Göran Andersson" <guffa@guffa.com> wrote in message
news:eKWOB$gcGHA.3908@TK2MSFTNGP04.phx.gbl...
> If adding members dynamically would even be possible, it's far from a good
> idea. It's my personal opinion that reflection should be used as little as
> possible, and the idea of altering an existing class goes far beyond that.
> It breaks the fundamental principles of object oriented programming.
>
> Can't use inheritance to expand on the class?
>
> public class MyClass : ExistingClass {
>
> private int id;
>
> public MyClass(int id) : base() {
> this.id = id;
> }
>
> public int Id { get { return this.id; } set { this.id = value; } }
>
> }
>
> Mannie wrote:
>> How can I add a member field to an already existing class during runtime,
>> or rather: add some hidden value to an object dynamically during runtime?
>>
>> 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.
>>
>> 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.
>>
>> Thanks!
>> Manfred Suttorp