In .NET, I understand that there is a garbage collector that will manage the memory that's being used during the execution of a program. This means that objects will be cleaned up when they go unused.
I was wondering if I could keep a static counter in a certain class that automatically updates when instances of that class are created or garbage collected. For example, if I create some instances of some CountableInstance class, then they could each have an InstanceIndex that keeps track of their current position based on when they were created.
Such a flow could look like this:
- Program starts
CountableInstance ctble0is created withInstanceIndex == 0CountableInstance ctble1is created withInstanceIndex == 1CountableInstance ctble2is created withInstanceIndex == 2CountableInstance ctble1goes unused and gets garbage collected
ctble0's index stays the samectble2's index becomes1
- Program ends
I'm guessing that keeping track of the number of CountableInstance instances would look like this:
public class CountableInstance
{
public static int total = 0;
public CountableInstance()
{
InstanceIndex = total;
total++; // Next instance will have an increased InstanceIndex
}
public CountableInstance(...) : this()
{
// Constructor logic goes here
}
public int InstanceIndex { get; private set; }
}
This takes care of how many instances there are and it also assigns the correct index to each new object. However, this implementation misses the logic that should happen when an instance is garbage collected.
If possible, how could I implement it? Would it also work to keep track of instances of objects that use a particular interface?