0

See my code. It is working, it writes to debug InstanceName of a Class2 instance (the name is Test). I want to change my code so that in Class Form1 instead of line Test = New Class2(NameOf(Test)) there will be line Test = New Class2(). And assigning the InstanceName will be made automatically in the Sub New in the Class2. So that the Sub New would look something like this:

Sub New()
    Me.InstanceName = **???Me.GetParent.Name???**
End Sub

Now this is the working example:

Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim Test As Class2
        Test = New Class2(NameOf(Test))
        Debug.WriteLine($"InstanceName: {Test.InstanceName}")
    End Sub
End Class

Public Class Class2
    Public Property InstanceName
    Sub New(InstanceName_ As String)
        Me.InstanceName = InstanceName_
    End Sub
End Class
4
  • 1
    What's the use of this? -- Test is not the name of the instance, it's the name of a local variable. Commented May 10, 2022 at 14:01
  • @Jimi I want to to the use of this too. But I'm not sure what the name of the instance would be other than "Test" here. I would say the working version is the best and only way, even see this question which we might even mark as a duplicate, and is almost identical to the working version. For OP's purposes, I think the term name of the instance is fine Commented May 10, 2022 at 16:34
  • @djv variables don't have names outside the context where they have been declared. If you pass your Test object to another Sub - Sub Hello(world As Class2) for example - that instance would now be named world. Commented May 10, 2022 at 16:41
  • @ÉtienneLaneville I understand, but that's just a reference to the same memory location the variable Test originally pointed to. In this example Test goes out of scope after Form_Load then the new reference, world, would be the only one. I guess Test is important to OP in some diagnostic way, and I would say the working example he has is the best [only] way to do this. Commented May 10, 2022 at 16:50

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.