<p>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</p>

<pre><code>dim a as New Foo()
dim b as New Foo()
</code></pre>

<p>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:</p>

<pre><code>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
</code></pre>

<p>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!</p>

[{'answer_id': 64015, 'author': 'TheSmurf', 'author_id': 1975282, 'author_profile': 'https://Stackoverflow.com/users/1975282', 'pm_score': -1, 'selected': False, 'text': "<p>It's likely throwing an error because you're never initializing _nextId to anything. It needs to have an initial value before you can safely add 1 to it.</p>\n"}, {'answer_id': 64033, 'author': 'Magnus Akselvoll', 'author_id': 4683, 'author_profile': 'https://Stackoverflow.com/users/4683', 'pm_score': 0, 'selected': False, 'text': '<p>It throws an error because _nextId is ReadOnly. Remove that.</p>\n\n<p><strong>Edit:</strong>\nAs you say, ReadOnly variables can be changed in a constructor, but not if they are Shared. Those can only be changed in shared constructors. Example:</p>\n\n<pre><code>Shared Sub New()\n   _nextId = 0\nEnd Sub\n</code></pre>\n'}, {'answer_id': 64090, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>This design is vulnerable to multithreading issues.  I\'d strongly suggest using Guids for your IDs (Guid.NewGuid()).  If you absolutely must use ints, check out the <a href="http://msdn.microsoft.com/en-us/library/system.threading.interlocked.aspx" rel="nofollow noreferrer">Interlocked</a> class. You can wrap all incrementing and Id logic up in a base class so that you\'re only accessing the ID generator in one location.</p>\n'}, {'answer_id': 64107, 'author': 'Remi Despres-Smyth', 'author_id': 8169, 'author_profile': 'https://Stackoverflow.com/users/8169', 'pm_score': 1, 'selected': False, 'text': "<p>ReadOnly variables must be initialized during object construction, and then cannot be updated afterwards.  This won't compile because you can't increment _nextId for that reason.  (Shared ReadOnly variables can only be assigned in Shared constructors.)</p>\n\n<p>As such, if you remove the ReadOnly modifier on the definition of _nextId, you should be ok.</p>\n"}, {'answer_id': 64108, 'author': 'Joel Coehoorn', 'author_id': 3043, 'author_profile': 'https://Stackoverflow.com/users/3043', 'pm_score': 1, 'selected': False, 'text': "<p>I'd do it like this.</p>\n\n<pre><code>Public MustInherit Class Unique\n    Private _UID As Guid = Guid.NewGuid()\n    Public ReadOnly Property UID() As Guid\n        Get\n            Return _UID\n        End Get\n    End Property\nEnd Class\n</code></pre>\n"}, {'answer_id': 64115, 'author': 'Compile This', 'author_id': 4048, 'author_profile': 'https://Stackoverflow.com/users/4048', 'pm_score': 0, 'selected': False, 'text': "<p>The shared integer shouldn't be read-only. A field marked <code>readonly</code> can only ever be assigned once and must be assigned before the constructor exits.</p>\n\n<p>As the shared field is private, there is no danger that the field will be changed by anything external anyway.</p>\n"}, {'answer_id': 64199, 'author': 'Magnus Akselvoll', 'author_id': 4683, 'author_profile': 'https://Stackoverflow.com/users/4683', 'pm_score': 3, 'selected': True, 'text': '<p>Consider the following code:</p>\n\n<pre><code>Public Class Foo \n    Private ReadOnly _fooId As FooId \n\n    Public Sub New() \n        _fooId = New FooId() \n    End Sub \n\n    Public ReadOnly Property Id() As Integer \n        Get \n            Return _fooId.Id \n        End Get \n    End Property \nEnd Class \n\nPublic NotInheritable Class FooId \n    Private Shared _nextId As Integer \n    Private ReadOnly _id As Integer \n\n    Shared Sub New() \n        _nextId = 0 \n    End Sub \n\n    Public Sub New() \n        SyncLock GetType(FooId) \n            _id = System.Math.Max(System.Threading.Interlocked.Increment(_nextId),_nextId - 1) \n        End SyncLock \n    End Sub \n\n    Public ReadOnly Property Id() As Integer \n        Get \n            Return _id \n        End Get \n    End Property \nEnd Class \n</code></pre>\n\n<p>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.</p>\n\n<p>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 :)).</p>\n'}, {'answer_id': 64261, 'author': 'Scott Dorman', 'author_id': 1559, 'author_profile': 'https://Stackoverflow.com/users/1559', 'pm_score': 0, 'selected': False, 'text': '<p>You said that "this will not compile because it throws an error" but never said what that error is.</p>\n\n<p>A shared variable is static, so there is only a single copy of it in memory that is accessible to all instances. You can only modify a static readonly (Shared ReadOnly) from a static (Shared) constructor (New()) so you probably want something like this:</p>\n\n<pre><code>Public Class test\n   Private Shared ReadOnly _nextId As Integer\n   Private ReadOnly _id As Integer\n\n   Public Shared Sub New()\n      _nextId = _nextId + 1\n   End Sub\n\n   Public Sub New()\n      _id = _nextId\n   End Sub\nEnd Class\n</code></pre>\n\n<p>(I think that\'s the right syntax in VB.) In C# it would look like this:</p>\n\n<pre><code>public class Test\n{\n   private static readonly int _nextId;\n   private readonly int _id;\n\n   static Test()\n   {\n      _nextId++;\n   }\n\n   public Test()\n   {\n      _id = _nextId;\n   }\n</code></pre>\n\n<p>}</p>\n\n<p>The only problem here is that the static constructor is only going to be called once, so _nextId is only going to be incremented one time. Since it is a static readonly variable you will only be able to initialize it the static constructor, so your new instances aren\'t going to be getting an incremented _id field like you want.</p>\n\n<p>What is the problem you are trying to solve with this scenario? Do these unique IDs have to be integer values? If not, you could use a Guid and in your contructor call Guid.</p>\n'}, {'answer_id': 64565, 'author': 'Anthony Mastrean', 'author_id': 3619, 'author_profile': 'https://Stackoverflow.com/users/3619', 'pm_score': 0, 'selected': False, 'text': '<p>I posted a <a href="https://stackoverflow.com/questions/41792/instance-constructor-sets-a-static-member-is-it-thread-safe">similar question</a> that focused on the multithreading issues of setting a unique instance id. You can review it for details.</p>\n'}]
['https://Stackoverflow.com/questions/63995', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8054/']