-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!"); } 
4
  • 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. Commented Jan 14, 2018 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. Commented Jan 14, 2018 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 Singletonclass, the countervariable is incremented wht every new instance. The =0assignment in the declaration line of counter is only executed once, at program startup, since counteris static. Commented Jan 14, 2018 at 16:51
  • Thanks, Heinz Kessler. Commented Jan 15, 2018 at 15:23

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.