I just stumbled upon a problem which took me hours to find the reason for.
I declared a class variable as ReadOnly because I wanted to set its value in the constructor of the class (all following code is example code, so it probably doesn't make much sense).
Private ReadOnly _content as String
Public Sub New(content As String)
_content = content
End Sub
Public ReadOnly Property Content As String
Get
Return _content
End Get
End Property
After a little bit of coding, I figured out that I wanted to do other stuff depending on the value of this variable, so I changed my code to:
Private ReadOnly _content as String
Public Sub New(content As String)
Me.Content = content
End Sub
Public Property Content As String
Get
Return _content
End Get
Private Set(value As String)
If Me.SetValue(Of String)(_content, value) AndAlso (_content = "foo") Then
'other stuff
End If
End Set
End Property
Private Function SetValue(Of T)(ByRef storage As T, value As T) As Boolean
storage = value
Return True
End Sub
But this changed code didn't work, the variable _content never got the value I passed in the constructor. Visual Studio 2019 showed no error and the code compiled and ran.
After a lot of trial and error I found out, that I forgot to remove the ReadOnly in the variable declaration, and that was the reason for my problem.
But why doesn't Visual Studio warn me about this situation, or why doesn't the program crash, when I try to set a ReadOnly variable outside of the constructor? What is this ReadOnly in the variable declaration good for, when it can only cause confusion and hard to find errors?