How can I see all the instances of a class?

advertisements

I have a short presentation at school for relations between classes (UML), and I want to show with code how composition and aggregation work in practical use and the difference between them. In order to do that however I want to be able to be able to see all active objects atm, to proove that the object I deleted and the object that was part of it are truly gone now.

This is a quick example of what I am trying to do:

List<Company>companies = new List<Company>(){
    new Company(){
      Name = "Greiner",
      new Boss(){
        Name = "Hugo",
      },
   },
};

Company comp = companies.FirstOrDefault();
companies.Remove(comp);

Now I want to somehow show that the Boss is gone along with the company, not just the (indirect) reference to him. So I thought of looking at all active objects.

Is there any way to do this? I am aware that the garbage collector is supposed to do this, but I dont want to tell my fellow students to just believe my words.

Also I do tend to think overly complicated, so my approach might be completely backwards, so any suggestions how to proove the differences between aggregation and composition are welcome.

Regards

Andreas Postolache


You can keep a static counter within your classes to keep count of the no. of instances created. Increment this counter in the constructor and decrease it in the destructor. The class structure sample is shown below.

public class Company
{
    public static int counter = 0;
    public Company()
    {
        counter++;
    }
    public string Name {get;set;}
    public Boss Boss { get; set; }
        ~Company()
    {
        counter--;
    }
}

public class Boss
{
    public static int counter = 0;

    public Boss()
    {
        counter++;
    }

    public string Name {get;set;}

    ~Boss()
    {
        counter--;
    }
}

Now you can see the no. of instances by printing this counter wherever required.

You can now instantiate your class Company and check the count of objects.

Company company = new Company(){ Name = "Greiner",  Boss = new Boss(){ Name = "Hugo" }} ;

Console.WriteLine("Company: " + Company.counter.ToString());
Console.WriteLine("Boss: " + Boss.counter.ToString());

company = null;

The output should result in Company: 1 and Boss: 1

Now on a Button Click write the following code

GC.Collect();
GC.WaitForPendingFinalizers();

Console.WriteLine("Company: " + Company.counter.ToString());
Console.WriteLine("Boss: " + Boss.counter.ToString());

Note that you will have to call the garbage collection methods to force immediate collection or else you cannot guarantee when the object will be removed by the GC.

The output will now show 0 for both Company and Boss.

Note: Use GC.Collect only in your classroom for demonstration purposes.