class within a class?

  • Thread starter Thread starter Craig Buchanan
  • Start date Start date
C

Craig Buchanan

If I declare a class within another class like:

Class ParentClass
...
Class ChildClass
...
End Class
End Class

How do I reference a property in the ParentClass in the ChildClass? If the
ChildClass is inherited from another class (like CollectionBase), do that
affect the reference?

Also, when an instance of ParentClass is created, is an instance of
ChildClass also created?

Thanks,

Craig Buchanan
 
Craig,
How do I reference a property in the ParentClass in the ChildClass?
You would need to give ChildClass a field of type ParentClass. When I need
this I normally define the parent to be part of the constructor.
Class ParentClass
...
Class ChildClass
...
Private Readonly m_parent As ParentClass

Public Sub New(ByVal parent As ParentClass)
m_parent = parent
End Sub
End Class
End Class
If the
ChildClass is inherited from another class (like CollectionBase), do that
affect the reference? No

Also, when an instance of ParentClass is created, is an instance of
ChildClass also created?
No, you need to explicitly create any ChildClass instances you need. If you
need a ChildClass created when you create a ParentClass I would do so in the
ParentClass constructor. You can create any number of ParentClass instances
for any number of ChildClass instances, including zero in both cases. In
other words you can have a ChildClass without a ParentClass, and you can
have a ParentClass without a ChildClass.

Class ParentClass
...
' continuing the above sample

Private ReadOnly m_child As ChildClass

Public Sub New()
m_child = New ChildClass(me)
End Sub
End Class

In the above sample, each parent has a reference to its lone child, that
child has a reference to its parent. Once all other references to both the
parent and child are gone, both objects will be garbage collected. In other
words you can the can references to each other and the GC will still remove
them from memory when no one else refers to them...

Hope this helps
Jay
 
Hi Craig,

In addition to what Jay has explained.

At the very least, nested classes give you a way to distinguish between
classes with the same name.

Class CarFactorySupplier
Class Widget
End Class
End Class

Class PlumbingBitsSupplier
Class Widget
End Class
End Class

In this sense the enclosing classes act in the same way as Namespaces to
provide a means of differentiating between the two (or more) sorts of Widgets.

As Jay, says, it's not necessary for the Parent class to actually use the
Child class within itself. The child would be nested to give it context, but
exist solely to provide additional services to users of the Parent class.

Regards,
Fergus
 
Back
Top