That isn't your code: I can tell for two reasons.
1) It won't compile - C# is case sensitive, and
Public
is not the same as
public
2) Your
Singleton
class as shown doesn't contain a
getInstanse
method, which is crucial to your problem.
The whole idea of a singleton class is that there is one and only one instance of the class in the system - so the constructor is always declared as
private
, not
public
so it can only be created inside the class itself. Normally that would be in a
GetInstance
method or similar, but the instance would be retained in a
private static
variable inside the class:
class Singleton
{
private static int counter = 0;
private static Singleton instance = null;
private Singleton()
{
counter++;
Console.WriteLine("Counter-" + counter);
}
public void getMessage(string s)
{
Console.WriteLine(s);
}
public static Singleton GetInstance()
{
if (instance == null) instance = new Singleton();
return instance;
}
}
class Program
{
static void Main(string[] args)
{
Singleton objSingleton = Singleton.GetInstance();
objSingleton.getMessage("Hi This is my first message!");
Singleton objSingleton2 = Singleton.GetInstance();
objSingleton.getMessage("Hi This is my second message!");
Console.ReadLine();
}
}
And that's why you only ever get a counter of 1: only one instance is ever created.