I have been trying to generate a Factory supposed to return a different object of a common interface (say Item) according to the input parameter (I call it a context) of the function getItem(A context)
Now, assume I define a new type of context: B which inherits from A.
I wanted to return a different item depending on whether the object passed to the factory was of class B or A.
I tried to do as follows (overloading the method):
class Factory
{
static Item getItem(A context) {...}
static Item getItem(B context) {...}
}
This works fine if I do something like this:
B bContext=new B();
Item it=Factory.getItem(bContext);
However, if I cast and object to type A:
A bContext=(A) new B();
Item it=Factory.getItem(bContext);
the first factory method is called.
I thought that polymorphism would ensure the execution of the second method even after the cast, and I would like to know if I missed something?
I am aware that I could keep having a single method and use the is operator to check what the type of the variable is, but I thought the solution I presented above was a bit more elegant.
Overloading is decided at compile-time (aside from using dynamic typing in C# 4) based on the compile-time type of the arguments – and in your last snippet, the compile-time type of the argument is
A, so it callsFactory.getItem(A).Only virtual method calls are polymorphic (using overriding), where the actual execution-time type of the target object to decide which implementation to call. If it makes sense for
AandBto have a virtual method (overridden inB) which can be called byFactory.getItemto handle the differences, that’s great… otherwise you’re stuck with either dynamic typing or something likeis.