3
Reply

Self-Registering classes in C#

viperashu

viperashu

Oct 8 2004 2:11 AM
6.5k
I have to make a program that implements a Shape Factory (that is a container that keep all kind of geometric shapes). The trick is, it has to be developped in such a way, to allow adding of new shapes (classes derived from a base abstract class "Shape") without modifing any of the main program's code... I've done it in C++... and it is something like that: //in main program: class Shape { virtual void Draw() = 0; //abstract } //in new file (added afterwards... ) class Circle : Shape { void Draw() {...} } namespace { //by initializing this const, i actually call the function RegisterCircle(...), that // registeres this class (addes some information in a vector) const bool registered = RegisterCircle(...); } because of namespaces in C++, this is OK... But in C#, I can not have variables inside a namespace (not included in a class). So I could use that variable, as a STATIC one, inside my "Circle" class. This would be ok, but for one thing: in C#, no variable (even a static one) gets initialized until its owner class is instantiated or a static member is called (used) in a program... And I can not instantiate or call a static member from the main program, because I'm not allowed to modify main program. So, please help!!!

Answers (3)