I was in an interview yesterday and one of the questions was what is a singleton and how do you implement it.
Solution #1 from MSDN:
using System;
public class Singleton
{
private static Singleton instance;
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
I gave the simplest solution (solution number 1 from msdn's implementation), while he wanted the thread-safe one (solution number 3).
Solution #3 from MSDN:
using System;
public sealed class Singleton
{
private static volatile Singleton instance;
private static object syncRoot = new Object();
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new Singleton();
}
}
return instance;
}
}
}
What is intriguing me is the private constructor in msdn's example. I did not know such a thing existed.
Taking a look at msdn on it
public class Counter
{
private Counter() { }
public static int currentCount;
public static int IncrementCount()
{
return ++currentCount;
}
}
I then ask:
Why would you have a class that has only static members and thus would like to prevent instances of it being created and hence the use for a private constructor - instead of making the class static ?!
P.S.: The question is not about singletons - is about describing a scenario where I would choose to create an instantiable class that has static members only (and thus eventually creating the need for a private constructor) instead of using a static class.