Hi Guys
Just for curiosity I modified the program obtained in the following website.
http://www.java2s.com/Code/CSharp/Language-Basics/Useastaticfieldtocountinstances.htm
Output expected is:
Current count: 1
Current count: 2
Current count: 3
Current count: 4
Current count: 5
But program is producing following output:
Current count: 1
Current count: 1
Current count: 1
Current count: 1
Current count: 1
Anyone knows please explain the reason.
Thank you
using System;
class CountInst
{
int count;
public CountInst()
{
count++;
}
public int getcount
{
get { return count; }
}
}
public class CountDemo
{
public static void
{
CountInst ob;
for (int i = 0; i < 5; i++)
{
ob = new CountInst();
Console.WriteLine("Current count: " + ob.getcount);
}
}
}
Posted Oct 4, 2007, 3:58 PM
Thank you very much for the explanation, Alan
AlanPosted Oct 4, 2007, 3:39 PM
Hi Maha,
As the code currently stands, the 'count' field of every CountInst object will be '1'. This is because 'count' is an instance field (not a static field) and so it's reset to zero each time and the constructor then increments it to one.
In addition, you're only creating one CountInst object, not five.
I don't know how it was before but the following revised code will work as expected:
using System;
class CountInst
{
static int next;
int count;
public CountInst()
{
count = ++next;
}
public int getcount
{
get { return count; }
}
}
public class CountDemo
{
public static void Main()
{
for (int i = 0; i < 5; i++)
{
CountInst ob = new CountInst();
Console.WriteLine("Current count: " + ob.getcount);
}
}
}