Simple example to count the number of times a class has been created and how many instances of that class are still alive.
git clone https://github.com/mwcaisse/ClassCounter.git
cd ./ClassCounter/src/ClassCounter
dotnet run 150
NonInheritableCountable: Created: 600 Alive: 0
ImCounted: Created: 150 Alive: 0
StayingAlive: Created: 1200 Alive: 400
ImCountedAsWell: Created: 300 Alive: 0
Simply inherit from ClassCounterBase on the class(es) you wish to enable counting on.
public class ClassIWantToCountWithInheritance : ClassCounterBase
{
}
####Advantages
- Only need to add the base class to enable counting, no need to add code to the constructor and deconstructor. Any changes made to the API will not require updating the class.
####Disadvantages
- You need to inherit from the BaseClassCounter class, which will not allow you to inherit from another class.
- Need to modify the class to enable instance counting.
Add the ClassCounter.InstanceCreated to the constructor and ClassCounter.InstanceRemoved to the deconstructor.
public class ClassIWantToCount
{
public ClassIWantToCount()
{
ClassCounter.InstanceCreated(this);
}
~ClassIWantToCount()
{
ClassCounter.InstanceRemoved(this);
}
}
####Advantages
- You are free to inherit from which ever class you choose
####Disadvantages
- You need to add 2 lines manually to the constructor + deconstructor, and will need to change them manually if ClassCounter API changes.
- Need to modify the class to enable instance counting.
Both of these methods require you modify the class directly to enable instance counting. Ideally it would be nice to have a RegisterForInstanceCounting(Type t) method that enables instance counting for that type without modifying the class. I was not able to find a way to do this without modifying the .NET runtime.
Both methods also make use of a static class to perform the counting. This doesn't allow you to have different objects for counting different classes. If that is desired it wouldn't be too hard to modify ClassCounter to be non-static. In doing so you would have to pass the instance of ClassCounter you wish to use to count to the constructor of each object. Depending on the use this may or may not be desirable.