I have a situation where I want to override the method of the base class in order to slightly change the return type of the method. By a small change, I mean returning an object that inherits from an object that would be returned by the method in the base type ... in fact, a little code will simplify this ...
class Program { static void Main(string[] args) { var obj = new ParentClass(); Console.WriteLine("Parent says: " + obj.ShowYourHand()); var obj2 = new ChildClass(); Console.WriteLine("Child says: " + obj2.ShowYourHand()); Console.ReadLine(); } } public class ParentClass { public string ShowYourHand() { var obj = GetExternalObject(); return obj.ToString(); } protected virtual ExternalObject GetExternalObject() { return new ExternalObject(); } } public class ChildClass : ParentClass { protected virtual new ExternalObjectStub GetExternalObject() { return new ExternalObjectStub(); } } public class ExternalObject { public override string ToString() { return "ExternalObject"; } } public class ExternalObjectStub : ExternalObject { public override string ToString() { return "ExternalObjectStub"; } }
The problem is that the obj2 instance does not call its version of GetExternalObject (), but rather uses its parent implementation.
I think it is, because in the code
var obj = GetExternalObject();
It is assumed that the obj type will be ExternalObject in the parent class. However, I realized that C # cannot distinguish between methods based on return type.
I know that there are other solutions to the problem, such as defining an IExternalObject, so don't get too stuck with this. All I wanted to know is what it thinks that the GetExternalObject child classes are not called even by the child class itself?
Or am I doing something completely stupid ?:-)
source share