Interview Questions Headline Animator

Wednesday, July 29, 2009

Singleton Vs. Static Class

Well I was asked this question once. “What is a singleton design pattern and why should I use it? Why not use a static class instead?”

And it was quite surprising how it went. I said that Singleton is used when you need to maintain state. Static classes are used when you want to club together a bunch of stateless methods that do something irrespective of which instance calls these methods. Math class is a good example.

So he asked me, can I not maintain state in a static class? So I said if you want to instantiate something in a static class how would imageyou do it? And surprisingly he told me that he would do it in a static constructor. I asked him, is it possible to instantiate anything in the static constructor or even declare an instance type in a static class? And he asked me is it not possible? I said it is not as far as I know and he asked me if I am sure.

Now the way the questions were asked about this subject, I was quite surprised. The interviewer looked quite convinced that instance types can be declared in a static class. I am surprised how he was allowed to take the interview in the first place. Or was he checking my confidence?

I wonder.