Counting instances of class

mrdance

Member
Joined
Nov 24, 2003
Messages
16
Is there an easy way to get number of objects created from a class?

Thanks / Henrik
 
Last edited by a moderator:
You could have a global variable that you increment everytime you create a new object from the specific class.

/Kejpa
 
You could implement a reference counting scheme in the class itself.
Add a shared (vb) or static (C#) variable to the class and in the constructor (Sub New) increment it and in the Desctructor (Finalize method) decrement it.
The shared variable will then be the number of objects created that havent yet been garbage collected.
 
Sounds nice but it never reaches finalize. I am listening to a tcp socket. Right now, after your answer, I call finalize when I receive an error on the socket. In finalize I decrease the activeConnections variable. It seems to work ok but it bothers me that it never reaches finalize by itself.

Thanks / Henrik
 
Finalize will be called sooner or later - however garbage collection is lazy by design. If you want more control search in MSDN for info on IDisposable.
 
Back
Top