Click here to Skip to main content
15,885,365 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I created a static variable in a class and incrementing in the constructor, thinking that whenever I created an instance to the class, the static variable will be reset to 0. To my utter surprise, the first time when I created the object to the class, static variable(Counter) is incremented to 1. The second time when I created the object to the class, the static variable is retaining the incremented value(1). Is this the behavior of static?

What I have tried:

class Singleton
   {
       private static int counter = 0;
       Public Singleton()
       {
           counter++;
           Console.WriteLine("Counter-" + counter);
       }
   }

  static void Main(string[] args)
       {
           Singleton objSingleton = Singleton.getInstanse;
           objSingleton.getMessage("Hi This is my first message!");
           Singleton objSingleton2 = Singleton.getInstanse;
           objSingleton.getMessage("Hi This is my second message!");
       }
Posted
Updated 14-Jan-18 5:45am

1 solution

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:
C#
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.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900