Program to count number of objects created in C# – To count the total objects created, we need to have a static int variable say “int count” and count should be incremented in all the overloaded constructors of the class.
We know that once we create object of the class, the class constructor will be called and count variable will be incremented.
Objects Count program example:
/*
* C# program to count objects
*/
class A
{
// Hold the count of objects created
// of this class
private static int count = 0;
/*
* count should be incremented in all overloaded constructor
*/
public A()
{
count++;
}
public A(int a)
{
count++;
}
// Return object count
public static int getCount()
{
return count;
}
}
/*
* Test program to count object instances C#
*/
class Program
{
static void Main(string[] args)
{
A o1 = new A();
A o2 = new A(10);
// So for total 2 object created
Console.WriteLine("Object created so for: " + A.getCount());
A o3 = new A(15);
A o4 = new A(15);
// At this point, so for total 4 object created
Console.WriteLine("Object created so for: " + A.getCount());
}
}
Output:
Object created so for: 2
Object created so for: 4