Search code examples
.netvb.netbasic

Accessing an object's parameter from an object inside it


I'm coding a program in which I have a class inside another class. I need to know if I can access properties of the external class from the internal one.

Something like this:

Module mod1

    Public Class c1
        Public var1 As Integer = 3

        Public Class c2

            Public Sub doSomething()
                'I need to access var1 from here. Is it possible?
            End Sub

        End Class

    End Class

End Module

Thank you so much in advance for your help!

EDIT: Example of what I want to do

Dim obj1 As New c1 'Let's suppose that the object is properly initialized
Dim obj2 As New obj1.c2 'Let's suppose that the object is properly initialized

obj2.doSomething() 'Here, I want to affect ONLY the var1 of obj1. Would that be possible?

Solution

  • You are still going to need to create a link between those two objects somewhere. Here is an example of how you could do it.

    Dim obj1 As New c1
    Dim obj2 As New c2(obj1)
    
    obj2.doSomething()
    

    doSomething can now affect both variables defined in c1 and c2. Implementation:

    Public Class c1
        Public var1 As Integer = 3
    End Class
    
    Public Class c2
        Private linkedC1 As c1
    
        Public Sub New(ByVal linkedC1 As c1)
            Me.linkedC1 = linkedC1
        End Sub
    
        Public Sub doSomething()
            'I need to access var1 from here. Is it possible?
            linkedC1.var1 += 1
        End Sub
    
    End Class