I have an object, say Dog. For each Dog the DB generates an unique identificator – ID.
But before saving the Dog in the DB I should generate a temporary (negative ID).
So, I created a shared (static) _lastId = 0 in the Class Dog.
In the Dog’s constructor I just decrement the lastId.
But once I save the dog in the DB or the Dog “dies” in the Garbage collector, the negative ID is not used anymore for that object, so could be used by other Dogs, that are alive but not saved.
because max Integer = 2,147,483,647, if I do a lot of generation-supressions of large lists of Dog’s I could exceed the maximum limit of the integer…
Private Shared _LastId = 0
Public Sub New()
Me.Id = _LastId - 1
What “recycling” mecanism could be used here to prevent the overflow?
Three options
1
Use a separate TempID that is Int64.
Override Equals and == to be smart enough to use the either TempID or ID.
But don’t change the Hash when the object gets a real ID.
2
Or use Int64 for the ID (temp and real).
On the positive side you happen to only use Int32.
3
Implement Dispose on the Dog and give back the -ID there.
And give back the -ID when the Dog gets a positive ID.
Have HashSet of recycled -ID and take from that list before getting a new -ID.