Nested Classes in VB.Net

JackOfHearts

New member
Joined
Mar 29, 2005
Messages
3
Programming Experience
10+
Many apologies if this is in the wrong forum. I am a new user and cannot see a more relevant one.

Could someone explain why the following code will not work for me? I am an experienced programmer but somewhat inexperienced in OOP and VB .NET in particular.

What I am trying to do is to get instances of the inner nested classes to talk directly to each other without reference to the instance of the outer class.

The code fails in the IDE because the reference to Object3 in class Class2 is not declared. It is not declared in Class2 but it is in the outer class (Class1) which to my understanding should be accessible from the inner class.

VB.NET:
Public Class Class1
Private Class Class2
Function Method2()
MsgBox("I am Method2 as defined in Class2")
Object3.Method3()
End Function
End Class
Private Class Class3
Function Method3()
MsgBox("I am Method3 as defined in Class3")
End Function
End Class
Sub New()
Dim Object2 As New Class2
Dim Object3 As New Class3
Object2.Method2()
End Sub
End Class
I have tried various ways to overcome this problem but to no avail. I think that I am suffering from trying to take too many new ideas on board at one time here. Have any of you more experienced people any suggestions on this?
 
Last edited by a moderator:
Hello and welcome to the forum :)

You need to read up on variable scope.
One way to solve this is to create a shared variable at Class1 level. Then you can use it from within class2:
VB.NET:
Public Class Class1
    Private Shared Object3 As New Class3()
    Private Class Class2
        Function Method2()
            MsgBox("I am Method2 as defined in Class2")
            Object3.Method3()
        End Function
    End Class
    Private Class Class3
        Function Method3()
            MsgBox("I am Method3 as defined in Class3")
        End Function
    End Class
    Sub New()
        Dim Object2 As New Class2()
        ' Dim Object3 As New Class3()
        Object2.Method2()
    End Sub
End Class
Another way would be to declare the Object3 variable in Class2.

Please try to use the code blocks to make the code more readable :).

Happy Object Oriented Programming.
 
Nested classes now working okay

Paszt,

Creating Object3 as a shared variable in Class1 works great for my intended application.

The option of declaring Object3 in Class2 would not work as I also need Object3 to reference Object2 in reverse which would create a chicken and egg situation. By creating both objects as shared variables in Class1 I will be able to avoid this.

Please accept my apologies for the non-indented code. It was originally indented but this somehow got lost during the cut and paste process.

Many thanks for your assistance.

JackOfHearts.
 
Back
Top