Rhino Mocks 2.7.1: Virtual Calls From Constructors

time to read 2 min | 318 words

In many ways, I feel that I'm still a C/C++ programmer, despite 5 or so years of almost exclusive .Net work. I found myself playing with the scope of the variables inside a method, trying to make sure that they would only be allocated once. It's only after I did it that I realized that it just doesn't matter for the CLR, since local variables has the same lifetime as their method and are only allocated once.

Today I had a bug that came from the same C++ thinking, I didn't consider what would happen if a mocked class constructor makes a virtual method call. I store all the state for the mocked objects' that a MockRepository generate in a hash table keyed to the object identity, and when a method call is intercepted, I uses the this pointer to find the correct state for the call.

The problem with a virtual method call from the constructor is that it calls the most derived override method, which is exactly opposite from how it is done in C++, where the method table is changed as the object is being construct (or de-construct). I actually blogged about the subject not long ago.

Because the object has not finished initializing yet, it is not yet stored in the repository, and so it can't find the state for the object, and then bad things happen :-)

Thanks for David for finding out the bug. I decided to ignore virtual method call from constructors, since I can't really see a way that this will be useful. If you create an expectation in the constructor, how are you going to meet it?

Anyway, you probably already know that you can find the source and the binaries here, but only if you look hard.