0

Why output is 2?

class Cat { public static int count=0; public Cat() { count++; } } static void Main(string[] args) { Cat c1 = new Cat(); Cat c2 = new Cat(); Console.WriteLine(Cat.count); }

25th Apr 2018, 10:58 PM
Elvis Vasquez
Elvis Vasquez - avatar
4 Respostas
+ 3
For additional reading, here are bite-sized chunks that explain static along with the other keyword "public" (vs private): https://csharp.2000things.com/2011/02/28/256-using-static-fields/ https://csharp.2000things.com/2011/03/01/257-private-static-fields/
25th Apr 2018, 11:49 PM
Kirk Schafer
Kirk Schafer - avatar
+ 1
Because you add to count two times. A static variable is the same throughout the program. When you call the constructor twice, you add to it each time.
25th Apr 2018, 11:12 PM
Ariela
Ariela - avatar
0
Thanks, I think I understand, count++ = 1 so cat = 1 I call the constructor twice it mean cat c1 and cat c2 is adding up 2, it print 2, is it correct?
25th Apr 2018, 11:21 PM
Elvis Vasquez
Elvis Vasquez - avatar
0
Thanks
25th Apr 2018, 11:50 PM
Elvis Vasquez
Elvis Vasquez - avatar