Thursday, 22 August 2013

Is it possible to assign a ReadOnly variable in a child class?

Is it possible to assign a ReadOnly variable in a child class?


Suppose I have this parent class:
Public MustInherit Class Parent
' ReadOnly instance variables:
Protected ReadOnly str1 As String
Protected ReadOnly str2 As String
Protected ReadOnly str3 As String
' constructor:
Public Sub New()
End Sub
End Class


I want to assign these variables in a child class' constructor, and I want
them to be ReadOnly so they cannot be changed once assigned, like this:
Public Class Child
Inherits Parent
' constructor:
Public Sub New()
MyBase.New()
' can't assign the ReadOnly variables here!
' compile error: 'ReadOnly' variable cannot be the target of an
assignment
Me.str1 = "asdf"
Me.str2 = "qwerty"
Me.str3 = "foobar"
End Sub
End Class


How can I do this? If it's not possible, why not?

No comments:

Post a Comment