A Portion of Buff

Everybody else had one, so...

January 2004 - Posts

Do you know what your constructor is doing?

Earlier, Peter Torr posted about the differences between language-enforced rules and framework-enforced rules (calling class constructors, specifically).  An interesting and related thing I discovered a couple of weeks ago was that constructors are not guaranteed to be called at all by the framework, let alone twice.  Again, it involves emitting MSIL (or not, as we shall see), rather than C#, but it's still a useful/dangerous/so-what feature.

Here's the MSIL that CSC emits by default for an empty constructor:

ldarg.0
call       instance void [mscorlib]System.Object::.ctor()
ret

As you can see, the base constructor is automatically called.  This call, as CSC would have it, happens before anything else in the current constructor is executed.  The trick - you guessed it - is simply to omit this call.  A constructor then becomes:

ret

Marvellous.  And what's the big deal?  Well, it turns out to be a solution to a limitation I keep running into with NMock, namely that it cannot mock a class without a parameterless constructor (NMock creates testable sub-classes on the fly using Reflection.Emit).  I got so fed up of creating single-implementation interfaces or empty constructors just to mock a class that I decided to investigate, and that's what I came up with.  If constructing the base class is a chore (because of the parameters it takes), then don't call it.  If it doesn't have an empty constructor, so what?  I don't have to call it.

You do have to be a bit careful calling unmocked methods who rely on state that should have been initialised by the constructor, but in certain situations it makes life much much easier.

The code should make it into NMock in the next couple of weeks, if I can get my arse in gear.

Fowler on Inversion of Control
My esteemed colleague has a new article up on his site: "Inversion of Control Containers and the Dependency Injection pattern".  Don't let the title put you off, it's actually not that dull, and describes a useful pattern that we've been employing to great effect recently.
More Posts