Reputation: 28586
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?
Upvotes: 0
Views: 153
Reputation: 45096
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.
Upvotes: 1
Reputation: 43743
Simply resetting back to -1 once you reach the lowest possible value will probably meet your needs:
Public Sub New()
If _LastId > Interger.MinValue Then
Me.Id = _LastId - 1
Else
Me.Id = -1
End if
' ...
Upvotes: 0
Reputation: 13980
Why not keeping all unsaved new objects with the default value of 0? Or even better, use an ORM like NHibernate or Entity framework to handle this?
Upvotes: 0