Jake Freelander
Jake Freelander

Reputation: 1471

Is there a keyword that can make a class variable readonly from outside the class but not on the inside?

Basically, the readonly keyword doesn't let me modify a field after I first create the class instance. I could use a property but in this case its just extra overhead. Is there a keyword to make a class field readonly from only outside the class?

Upvotes: 0

Views: 219

Answers (3)

As others have stated, use a property. If you don't want to split the property into one Getter and one Setter then make the setter private.

Public Class Foo

    Public Property Abc() As Object
        Get
            Return Me.m_Abc
        End Get
        Private Set(value As Object)
            Me.m_Abc = value
        End Set
    End Property

    Private m_Abc As Object

End Class

However: The common way is to set the access level of the field to Friend making it accessible within the same assembly, but not from outside the assembly.

Public Class Foo

    Public ReadOnly Property Abc() As Object
        Get
            Return Me.m_Abc
        End Get
    End Property

    Friend m_Abc As Object

End Class

Upvotes: 1

Niya
Niya

Reputation: 253

No there isn't. This type is scenario is precisely why properties are provided in the first place. You get a whole lot of flexibility.

However, if you insist you want to use a read only field, you can use reflection to change the value:-

Public Class TestClass

    Public ReadOnly MyNumber As Integer

    Public Sub New()
        'Readonly fields can only be changed this way
        'in the constructor
        Me.MyNumber = 900
    End Sub

    Public Sub ChangeNumber(ByVal num As Integer)
        SetNumber(num)
    End Sub

    Private Sub SetNumber(ByVal num As Integer)

        Dim fi = Me.GetType.GetField("MyNumber")

        'Reflection can change the value of
        'a read only field after construction
        fi.SetValue(Me, num)
    End Sub

End Class

Note that this is a very terrible thing. Reflection shouldn't be used for this sort of thing as you're going to take a performance hit. Just use properties and save yourself the trouble.

Upvotes: 0

Orchid
Orchid

Reputation: 223

make the field private, provide getter and setter for it. Make the setter private. This way the value can be seen from outside the class by the getter,but, cannot be set/written from outside the class. this makes the property read-only from outside the class.

Upvotes: 1

Related Questions