Variable scope in nested classes
I have put together the following code to illustrate the problems I've been struggling with:
Public Class OuterClass
Private _OuterProp1 As Boolean = False
Public Property OuterProp1 As Boolean
Get
Return _OuterProp1
End Get
Set(ByVal value As Boolean)
_OuterProp1 = value
End Set
End Property
Protected Class InnerClass1
Private _InnerProp1 As Integer = 0
Private Sub InnerSub1()
If OuterProp1 Then
_InnerProp1 = 10
End If
End Sub
End Class
Protected Class InnerClass2
Private Sub InnerSub2()
_InnerProp1 = 5
End Sub
End Class
End Class
I need to be able to refer to outer class properties and variables in an inner class, and I need to have a variable in one inner class set in a different class. I've tried Public, Private, Protected, Friend and all kinds of combinations of them, and I can't figure it out. Can someone please help me? Thanks!
Re: Variable scope in nested classes
You can either create a new instance of the class, giving you a reference to a new instance of the public properties, methods, etc. You can also refer to an instance of the property in a previously declared class.
Alternatively, you could just declare them in a module if they need to be used between each class.
Re: Variable scope in nested classes
Thank you for your prompt reply. Unfortunately, I'm new to classes and I'm not sure how to do what you suggest. Specifically, how do I "refer to an instance of the property in a previously declared class"? Can you show me how to change my code to work as is, without defining modules or new instances of the classes?
Re: Variable scope in nested classes
Code:
Protected Class InnerClass1
Public _InnerProp1 As Integer = 0 '' or better define as property.
Private Sub InnerSub1()
If OuterProp1 Then
_InnerProp1 = 10
End If
End Sub
End Class
Protected Class InnerClass2
Private Sub InnerSub2(ByVal ic1 as InnerClass1)
ic1._InnerProp1 = 5
End Sub
End Class
Re: Variable scope in nested classes
Thanks again! I'll give it a try.