Design problem: How can I recognize an object's actual class when it's refered to by a variable of the object's parent class (or interface)?
Posted on 2005-04-20
I have a container class that has a property of type A.
A is an Abstract class (or it could be an Interface if the solution to this problem warrants it).
B, C, etc.... all derive from A (or again, they could all implement A, if it ends up being an interface). This allows me to have the container class's property hold an object of type B or C or etc...
I also have an overloaded method (seperate from all of these classes) that takes an object of these derived classes (one per class). I want to use it like this:
Container container = new Container();
B b = new B();
container.Property = b;
What I want to happen here is that the type of the object assigned to the property (i.e. B, C, etc...) would determine which overload of Method to use. Instead, it's looking at it as type A, the parent class that property is declared as.
I realize what I am really asking for is dynamic casting. I'd love to be able to right something like:
but that isn't allowed in C# (to my knowledge).
I suppose I could include a method in each subclass that returns an instance of itself as it's correct type. So, for example, B would have:
public B GetObjectOfActualType()
The problem with that approach is that I can't put a stub for that method into the parent class (or interface) because each sub-type's GetObjectOfActualType method would return a different Type and you can't change the return type of a method declared in an abstract class (or interface), right?
Anyway...I hope that I have adequately described my design goal and the problem. If not, I'll be around to clarify as needed.
Any and ALL help is appreciated.