user2150033 user2150033 - 6 months ago 9
Vb.net Question

Detecting or preventing assigment operator to a class

Is there any way to make a class can be only initialized at declaration.

Public Class AnyValue
Private value As Int32

Public Sub New(ByVal aValue As Int32)
value = aValue
End Sub
End Class

'I want to be able to do this:
Dim val As New AnyValue(8)

'But not this.
val = New AnyValue(9)


Or it is possible to stop the assignment or detect when the operator = is used.

Answer

Lets just say this - No, you can't do what you want. The closest thing to it that I can think of, is to hide the constructor and give static access to the consumer as follows:

Public Class AnyValue
    Private value As Int32

    Private Sub New(ByVal aValue As Int32) ' Note - private constructor
        value = aValue
    End Sub

    Public Shared Function Create(ByVal aValue As Int32) As AnyValue
        Return New AnyValue(aValue)
    End Function

End Class

'This will not work
Dim val As New AnyValue(8)

'This will not work
val = New AnyValue(9)

' This will work
Dim val As AnyValue = AnyValue.Create(8)

Now, if you look at this method of object creation, you can see that you can set all sort of rules for object construction. So, the client has very little input on the construction itself because how you construct the object is totally controlled by the object itself.