Q:

C# program to get the count of total created objects

0

C# program to get the count of total created objects

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program:

The source code to get the count of total created objects is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# program to get the count of total created objects

using System;

public class Counter
{
    static int count=0;

    public Counter()
    {
        count++;
    }

    public static int TotalObjects()
    {
        return count;
    }
}

class Test
{
    static void Main(string[] args)
    {
        Counter C1 = new Counter();
        Counter C2 = new Counter();
        Counter C3 = new Counter();

        Console.WriteLine("Total objects created: " + Counter.TotalObjects());
    }
}

Output:

Total objects created: 3
Press any key to continue . . .

Explanation:

In the above program, we created a class Counter that contains static data member count, and a constructor that increases the value of data member count by one each time when an object gets created.

Now look to the Test class that contains the Main() method. The Main() method is the entry point for the program. In the Main() method we created the three objects of Counter class. Then we printed the count of created objects using the TotalObjects() method on the console screen.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C# Basic Programs | Class, Object, Methods

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C# program to demonstrate the static constructor... >>
<< C# program to demonstrate the static class...