How to create a numbering system for custom class object

Hi everyone,

I am trying to develop a set of c# components in Visual Studio and I would like to find a way to assign an element ID (in ascending order from 1) to instances of custom classes.

Here is what I have found online and tried so far:

  • Add a static int counter to the class, counter++ in the constructors and counter-- in the finaliser. The issue that I found in this approach is that the Duplicate() method of the class may be called when transfering data from one component to another, and this will increase the counter without the creation of an actual new object.
    I also tried to increase the counter outside the constructors only in the component that actually creates brand new instances, but I don’t particularly like the idea of the counter increasing indefinitely every time the solution is recomputed.
  • Add a static List to the class and add a new WeakReference to the list every time a brand new instance is created. I thought I could also iterate through the list and remove the references that are not active anymore, but this doesn’t seem to work either and every time I recompute the solution the list keeps growing.

My issues here seem to be how to deal with the recomputation of the solution and how to deal with input change in the components that generate the new instances.

Any help and suggestion will be very much appreciated.


I am not sure if it could work on your problem but singleton class could help to count instances of custom classes