Living .NET...

Musings on .NET, and the like - Manoj G [MVP, Connected Systems Developer]

Interesting behavior - Virtual method dispatch in .NET

Try these steps and see what happens.

Step 1 : Let's say I have a Base class and an overridable (virtual method). Now, I derive a class from this and override the virtual method.
Step 2 : In both these classes, have the constructor call the virtual method.
Step 3: Create an instance of the derived class using the base class reference. Here's what I mean: dim obj as Base = New Derived()

Now, you have to agree with me that the base class constructor is called before the derived one?? If yes, which method is dispatched in the base class constructor - the method in the base or the method in the derived? Whatever be the answer - why would it happen this way?

The answer to the "which" part of the question is - the derived class method is dispatched.
This can have interesting consequences -  You can end up invoking an instance method of an object before its constructor !!!! So what happens if you access instance members Inside that virtual method?  Answer - Catastrophe!. But it is okay. It takes a genius to do this extraordinarily stupid thing. We are just normal developers. Aren't we ??

Posted: Thu, Dec 25 2003 17:41 by Manoj G | with no comments
Filed under:
Leave a Comment

(required) 

(required) 

(optional)

(required)