Hi, i know my following question may seem rather stupid but im having some problems understanding the static concept especially in the following code and id appreciate some help.
4: using System;
5:
6: public class myClass
7: {
8: static public int sctr = 0;
9: public int ctr = 0;
10:
11: public void routine()
12: {
13: Console.WriteLine(“In the routine - ctr = {0} / sctr = {1}\n”,
14: ctr, sctr );
15: }
16:
17: public myClass()
18: {
19: ctr++;
20: sctr++;
21: Console.WriteLine(“In Constructor- ctr = {0} / sctr = {1}\n”,
22: ctr, sctr );
23: }
24: }
25:
26: class TestApp
27: {
28: public static void Main()
29: {
30: Console.WriteLine(“Start of Main method...”);
31:
32: Console.WriteLine(“Creating first object...”);
33: myClass first = new myClass();
34: Console.WriteLine(“Creating second object...”);
35: myClass second = new myClass();
The output is as follows:
Start of Main method...
Creating first object...
In Constructor- ctr = 1 / sctr = 1
Creating second object...
In Constructor- ctr = 1 / sctr = 2
From what i have understood, the SCTR is a static and is therefore only initialized only at the begining of the program and then never again hence why it can increment. CTR on the other hand is public so Line 9 which sets it to 0 each time the myclass object is accessed.
if the above is right, could someone please clarify why there is a static in line 28 as the description i found in my c# book wasnt particularly useful.