C# - Count the Total Created Objects (Instances) of a Class

In this example, we will learn how to get the count of total created objects (instances) of a class using C# program?
Submitted by Nidhi, on November 08, 2020 [Last updated : March 22, 2023]

Here, we will create a class and count the total created objects using static data members.

C# program to get the count of total created objects

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# - Count the Total Created Objects (Instances) of a Class

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.

C# Basic Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.