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

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


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


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!

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.