Years and years ago, I was searching for a new job. I had some development experience, and some OO exposure, but not too much - I was probably only a few years out of school. I had an interview where I was asked:
"What's a private constructor, and how would you use it?"
Wait, a private constructor you say? Why would anyone want to keep the constructor private? If it's private, then they can't instantiate the class and then.....oh.
I didn't say any of those things. I think I answered with the answer guaranteed to win you a pass to the second round of interviews:
"Um... I have no idea".
Yeah, so no job there. But I did have that question follow me around, haunting me for weeks. I learned about the private constructor, and how to use it - how it works in the Singleton pattern, etc.
Flash-forward to today.
Brian Hitney and Chad Brooks came through town with a great
MSDN Roadshow. I enjoyed every part of it, but especially this:
Brian was demoing the asp:movie control in the ASP.Net futures and showed a small utility class he was using to hold the media objects. He asked everyone what the CLR does if you omit the constructor of a class. A guy answered that the CLR creates a constructor automatically. Brian followed up by asking what the access level of the constructor was, to which the guy answered 'internal'.
This is a great answer.
I would wager not many folks in the room thought this was the answer, but internal is one of those modifiers that developers don't often use, and so when 'internal' was offerred, folks were too intimidated by their ignorance of internal to offer any debate. It even gave Brian pause, but we moved on, into the meat of the demo.
Curiosity piqued, I spent 5 minutes creating a class with no constructor, compiling it, and reviewing it in
Reflector. Sure enough, the CLR has created a parameterless constructor for me:
public class Miranda
{
// Methods
public Miranda();
}
At the end of the demo, I report my findings to Brian. He asks, "What would you do to keep the constructor from being created?", and in a triumphant, redemptive moment, I answer
"You would create a private constructor"
Note: The class is called Miranda because the way in which the CLR creates this constructor for you is very similar to a line the police use when reading someone their Miranda rights: "If you cannot afford a constructor, one will be appointed for you by the CLR."
posted @ Wednesday, August 29, 2007 1:52 PM