Search code examples
vb.netoopinitializationinstance

Assign new instance to other instance


I'm trying to do something like this in VB.NET:

Class Something()

    Sub New()
        Me = OtherThing       'Other instance of the same class 
    End Sub

End Class

During object initialization, I want to switch the current instance of the class with previously initialized instance of this class. I need control over the instances that are created.

In my code module, just trying to use it like this:

dim thng as Something = new Something 

I've tried all the variants of Me, MyBase, MyClass. Tried functions that return the right instance and so on. Don't want to use factory or after init assignment:

dim thng as Something = new Something

dim thng = OtherThing

Is it possible?


Solution

  • If you make the constructor public, then you're already in an impossible situation since you actually want to control the process of instantiation. You said Don't want to use factory. Sorry, but this is what I think is the best solution for your problem.

    Public Class Something
    
        Private Shared somethings As New List(Of Something)()
        Private Shared instanceLock As New Object()
    
        Public Property ID As Integer
    
        Private Sub New(id As Integer)
            Me.ID = id
        End Sub
    
        Public Shared Function GetInstance(id As Integer)
            SyncLock instanceLock
                Dim instance = somethings.SingleOrDefault(Function(s) s.ID = id)
                If instance Is Nothing Then
                    instance = New Something(id)
                    somethings.Add(instance)
                End If
                Return instance
            End SyncLock
        End Function
    
        Public Shared Function Count() As Integer
            Return somethings.Count
        End Function
    
    End Class
    

    Use a private constructor and static function to return new and existing instances. Create a new instance or target an existing instance by passing an ID

    Dim something1 = Something.GetInstance(1)
    Debug.Print($"Something1.ID = {something1.ID}")
    Debug.Print($"Count = {Something.Count}")
    Dim something2 = Something.GetInstance(2)
    Debug.Print($"Something2.ID = {something2.ID}")
    Debug.Print($"Count = {Something.Count}")
    Dim someOtherThing = Something.GetInstance(1)
    Debug.Print($"SomeOtherThing.ID = {someOtherThing.ID}")
    Debug.Print($"Count = {Something.Count}")
    

    Something1.ID = 1
    Count = 1
    Something2.ID = 2
    Count = 2
    SomeOtherThing.ID = 1
    Count = 2