Back to basics!!! How to get total number of objects is created for a Class

We can get the actual number of objects created for class throughout lifetime,this can be achieved as follows
We need to declare the static integer to store the number/count of the object created.
And we just need to increment integer/counter by 1 every time constructor is getting called.

class Program
{
public static void Main()
{
Console.WriteLine(“Number of Objetcs :- ” + SampleClass.noOfObjects);
SampleClass s1 = new SampleClass();
Console.WriteLine(“Number of Objetcs :- ” + SampleClass.noOfObjects);
SampleClass s2 = new SampleClass();
Console.WriteLine(“Number of Objetcs :- ” + SampleClass.noOfObjects);
}

public class SampleClass
{
public static int noOfObjects = 0;
// Add counter in Constructor,
// Each time class object is call Counter will get incremented and
// we can get final value of the number by printing/getting the value of
// noOfObjetcs.

public SampleClass()
{
noOfObjects++;
}
}

}

Number of Objetcs :- 0
Number of Objetcs :- 1
Number of Objetcs :- 2
Press any key to continue . . .

Please share, if you know any other ways to achieve this.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s