2
Answers

NP49 Reason for different output

Maha

Maha

17y
1.9k
1

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 Main()

    {

        CountInst ob;

 

        for (int i = 0; i < 5; i++)

        {

            ob = new CountInst();

            Console.WriteLine("Current count: " + ob.getcount);

        }

    }

}

Answers (2)