Ok lets say I have two classes with the same method(sampleMethod) which is overridden by the child: ObjectParent and ObjectChild
ObjectChild ExampleVariable = new ObjectChild();
(ExampleVariable as ObjectParent).sampleMethod();
Will this call the sampleMethod from ObjectChild or from ObjectParent??
I think it will call the sampleMethod from ObjectChild, but I want to make sure before I throw down a bunch of code based on that assumption.
Assuming it’s really a virtual method which is properly overridden (rather than just being hidden), it will call the
ObjectChildimplementation. That’s the whole point of virtual methods – that you don’t need to know the execution-time type at compile-time. For example, I can write a method usingStream.Read(e.g. by taking theStreamas a parameter) without knowing which implementation ofStreamit will end up using. At execution time that code could end up reading from the network, from memory, from disk… my method’s code neither knows nor case.Short but complete program demonstrating this: