Re: Using ReadOnly properly
I think you can only initialize ReadOnly fields when declaring them, or in the constructor:
Code:
Public ReadOnly Name As String = "ABC"
or
Code:
Public Readonly Name As String
Public Sub New()
Name = "ABC"
End Sub
Since you are talking about a module, only the first is an option.
If you do need to set the value at a later stage, consider a ReadOnly property instead. You can still make the private backing field writable:
Code:
Private _Name As String
Public ReadOnly Property Name() As String
Get
Return _Name
End Get
End Property
Now you can set the backing field to change the value of the property from within the same class (obviously not outside of the class).
In the same class, you can read and write:
Code:
'Read
MsgBox(Me.Name)
'Write
_Name = "DEF"
From the outside, any other class, you can only read:
Code:
'Read
MsgBox(classInstance.Name)
'Write
classInstance.Name = "DEF" ' readonly error (Name is readonly)
classInstance._Name = "DEF" ' access modifier error (_Name is private)
Re: Using ReadOnly properly
Quote:
Originally Posted by
Disyne
It is my understanding that a ReadOnly variable can only be set once and after that you would get an error when setting it.
This is another case when you simply need to consult the documentation.
Quote:
You can assign a value to a ReadOnly variable only in its declaration or in the constructor of a class or structure in which it is defined.
http://msdn.microsoft.com/en-us/library/z2b2c2ka.aspx