-5

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 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?

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

 static void Main(string[] args)
   {
       Singleton objSingleton1 = new Singleton();
       objSingleton1.getMessage("Hi This is my first message!");
       Singleton objSingleton2 = new Singleton();
       objSingleton2.getMessage("Hi This is my second message!");
   }
  • 2
    When writing an example, please write a *real* one rather than pseudocode. I'd also advise finding a good C# tutorial for the meaning of static. – Jon Skeet Jan 14 '18 at 16:35
  • 1
    If you're dealing with a properly implemented singleton then the constructor will only be run once and you're only going to be dealing with one instance. However you have not included all the code so we can not say for sure why you see that behavior. – juharr Jan 14 '18 at 16:44
  • I'm not sure, what "getInstance" does. From the code shown above, I see no singleton. Assuming that getInstance creates a new instance of the `Singleton`class, the `counter`variable is incremented wht every new instance. The `=0`assignment in the declaration line of `counter` is only executed once, at program startup, since `counter`is static. – Heinz Kessler Jan 14 '18 at 16:51
  • Thanks, Heinz Kessler. – Sunilkumar Mandati Jan 15 '18 at 15:23

1 Answers1

0

To simply put it, all instances you will create will share the static variable, and it will exist until the application is offloaded from memory

Owuor
  • 616
  • 6
  • 10