I would like to give a class a unique ID every time a new one is instantiated. For example with a class named Foo i would like to be able to do the following
dim a as New Foo() dim b as New Foo()
and a would get a unique id and b would get a unique ID. The ids only have to be unique over run time so i would just like to use an integer. I have found a way to do this BUT (and heres the caveat) I do NOT want to be able to change the ID from anywhere. My current idea for a way to implement this is the following:
Public Class test Private Shared ReadOnly _nextId As Integer Private ReadOnly _id As Integer Public Sub New() _nextId = _nextId + 1 _id = _nextId End Sub End Class
However this will not compile because it throws an error on _nextId = _nextId + 1 I don’t see why this would be an error (because _Id is also readonly you’re supposed to be able to change a read only variable in the constructor.) I think this has something to do with it being shared also. Any solution (hopefully not kludgy hehe) or an explanation of why this won’t work will be accepted. The important part is i want both of the variables (or if there is a way to only have one that would even be better but i don’t think that is possible) to be immutable after the object is initialized. Thanks!
Consider the following code:
Instead of storing an int inside Foo, you store an object of type FooId. This way you have full control over what can and cannot be done to the id.
To protect our FooId against manipulation, it cannot be inherited, and has no methods except the constructor and a getter for the int. Furthermore, the variable _nextId is private to FooId and cannot be changed from the outside. Finally the SyncLock inside the constructor of FooId makes sure that it is never executed in parallell, guaranteeing that all IDs inside a process are unique (until you hit MaxInt :)).