How do you calculate the total number of created objects for a particular class in C#/C++?
This could be one of the question to in any technical interview. So what is the solution??
suppose think that you have a class abc.
class abc
{
int x=10;
Console.WriteLine(a);
}
now if you create the object of the class:
abc a1=new abc();
abc a2=new abc();
now the total number of objects are 2. But how do you calculate it programatically??
Below is the solution:
class mainClass
{
static void Main(string[] args)
{
abc a1 = new abc();
abc a2 = new abc();
abc a3 = new abc();
abc a4 = new abc();
abc a5 = new abc();
abc a6 = new abc();
Console.WriteLine(abc.count);
}
}
class abc
{
public static int count = 0;
public abc()
{
count++;
}
}
Output:
6
Hope it helped you :)