C# Program to Get the Count of Total Created Objects
C# is a general-purpose programming language it is used to create mobile apps, desktop apps, websites, and games. In C#, an object is a real-world entity. Or in other words, an object is a runtime entity that is created at runtime. It is an instance of a class. In this article, we will create multiple instances or objects of a class and count the number of objects created in C#.
Approach:
- Create a class with the name DemoClass for which we are creating multiple objects.
- We create a class ( .i.e. GetCount) with the main method from which we will create multiple objects of the DemoClass.
- In the Democlass, we are going to define a static variable count and initialize it to 0.
- Create a constructor for DemoClass which increments the count whenever the object of DemoClass is created.
- Here we are defining it as static because a single copy of the variable is created and shared among all objects at the class level, so whenever we create a new object the value of count will not be lost.
- A static method (i.e. TotalCount ) is created to return the count value, Static methods are methods that are called on the class itself, not on an object.
- In the main method create multiple objects of DemoClass and call the TotalCount method using the class name (i.e. DemoClass).
Example 1:
C#
using System;
class DemoClass{
static int count = 0;
public DemoClass()
{
count++;
}
public static int TotalCount()
{
return count;
}
}
class GFG{
static void Main( string [] args)
{
Console.WriteLine( "Total objects = " +
DemoClass.TotalCount());
DemoClass C1 = new DemoClass();
DemoClass C2 = new DemoClass();
DemoClass C3 = new DemoClass();
Console.WriteLine( "Total objects = " +
DemoClass.TotalCount());
}
}
|
Output:
Total objects = 0
Total objects = 3
Example 2:
C#
using System;
class DemoClass{
static int count = 0;
public DemoClass()
{
count++;
}
public static int TotalCount()
{
return count;
}
}
class GFG{
static void Main( string [] args)
{
Console.WriteLine( "Total objects = " +
DemoClass.TotalCount());
DemoClass C1 = new DemoClass();
DemoClass C2 = new DemoClass();
DemoClass C3 = new DemoClass();
DemoClass C4 = new DemoClass();
DemoClass C5 = new DemoClass();
DemoClass C6 = new DemoClass();
Console.WriteLine( "Total objects = " +
DemoClass.TotalCount());
}
}
|
Output:
Total objects = 0
Total objects = 6
Last Updated :
30 Sep, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...