The question that I have is in regards to creating a shared field that is Static within an instance class. The code that I am going to display works perfectly fine. What I am really wanting to grasp is the understanding behind the logic. Here is a code snippet which is of a very basic class and a method which creates objects from this class and displays to the screen how many objects have been created.
public class Counter
{
private int value;
private static int ValueCounter = 0;
public Counter()
{
value = ValueCounter;
ValueCounter++;
}
public static int objectCount()
{
return ValueCounter;
}
}
Above is a very basic but working class. I am trying to keep it as simple and as basic as possible so that I get the understanding of it.
Below is now the code snippet that creates instances of the class and displays to the screen how many instances have been created.
private static void showObjectCounter()
{
Counter val1 = new Counter();
Counter val2 = new Counter();
Counter val3 = new Counter();
Counter val4 = new Counter();
int totalValue = Counter.objectCount();
Console.WriteLine("Total objects created = {0}", totalValue);
}
Now this is my question regarding this matter. When a new object is created the value field is independent of each instance hence each object gets there own copy. However the static field is a shared field and incremented with each new creation of an object. I was wondering if this increment value is saved after each creation of the new object i.e one object is created value is incremented to 1, then another object is created and the last value of the increment was at 1 so now it is incremented to 2 and so on for each new object creation.
Or does each new object that is created get incremented to 1 and then are all added together to find the total value of the objects created ?
It is a very basic and simple question but Iam fighting with myself over which is ryt or wrong prob because of the time of nyt that it is. Anyhow if anyone has a simple answer to a very simple question then please feel free to share it.
Thanks.