views:

97

answers:

2

Probem: A parent abstract class must be aware of all his existing child classes. The parent class must also be able to list all the class names of his child classes through a method.

Context: In my situation, the parent class is used to represent any input data type for a web form (such as email, text, boolean, integer, image, and so on). The child classes represent each specific data types. So there is a Boolean class, an Image class, an Integer class, etc.

The language I'm using is C#.

How would you do that?

edit: The reason why I need to know the child classes is because I need to know all the input data types available in order to list them. Also, I need to access the methods of each data type (child class) to get its properties.

So, for example, I need to get an instance of the Image class simply with the string "Image" that is stored in a database. If the base class knowns all its children, I will be able to ask it to get me the child represented by the string "Image", and it will return an instance of the Image class.

I thought of implementing it by making each child a Singleton, and adding itself to a list of children (at construction) that would be a private field of the base DataType class.

+2  A: 

You can check out this post. Looks like you need to iterate through known types and see if they are a subclass of the parent class using Type.IsSubclassOf

SwDevMan81
Thank you, I didn't know this way of doing it. For sure it would work, even though the cost if this operation seems a bit heavy.
asmo
+2  A: 

You can write in the constructor code that will notify some static class that something new was created.

Something like:

class A {
 A() {
  myBuilder.notifyMe(this);
 }
}

myBuilder is a static class with code:

void notifyMe(Object o) {
 // do whatever you want here
 // maybe something like
 someList.Add(typeof(o).Name)
}

edit: Ok, this solution, of course, requires that the subclasses are instantiated first. If you want to know all the subclasses when program starts I think the only way is to scan entire class path and check for each class is it subclass of wanted one.

Klark
This is not really an answer to the OP's question. This requires that the subclasses be instantiated first, which is probably not what he wants, and certainly not what he asked for.
Kirk Woll
Well this is how I initialy thought of implementing it. I tried to make each subclass a singleton in order to have them notify the static class automatically upon their unique construction, but it isn't working.
asmo
well they do not need to be singletons. Builder can have some hash map and every time when some class is created it will check in the hash is it already there and if it is not then that is the first instance of that class and you can do whatever logic you want. Give us your code, maybe someone will help you,
Klark