Private nested classes

.net, class, nested, oop, vb.net

Solution

Typically the Private nested class implements an interface or inherits another class, and the interface/base class is exposed. This is useful when you want to hide the implementation to the parent class. Something like this:

Module EntryPoint
    Sub Main()
        Dim OuterClassInstance As New OuterClass
        OuterClassInstance.NestedClassInstance.GetParentX()
    End Sub
End Module

Public Class OuterClass
    Public X As Integer = 123
    Public NestedClassInstance As ISomeImplementation = New NestedClass(Me)

    Private Class NestedClass
        Implements ISomeImplementation
        Private Parent As OuterClass

        Public Sub New(ByVal _Parent As OuterClass)
            Parent = _Parent
        End Sub

        Public Sub GetParentX() Implements ISomeImplementation.GetParentX
            Debug.WriteLine("X = " & Parent.X.ToString)
        End Sub
    End Class
End Class

Public Interface ISomeImplementation
    Sub GetParentX()
End Interface

Problem

I want to created a nested class that can only be visible to and instantiated from the parent class. But I also want to be able to use an instance of the nested class through a public variable of the parent class. I tried making the nested class private, or making the nested class' constructor private, but it won't compile. Is it possible to do this in .NET? This compiles and works, but the nested class can be used by anybody: ``` Public Class OuterClass Public X As Integer = 123 Public NestedClassInstance As New NestedClass(Me) Public Class NestedClass Private Parent As OuterClass Public Sub New(ByVal _Parent As OuterClass) Parent = _Parent End Sub Public Sub GetParentX() Debug.WriteLine("X = " & Parent.X.ToString) End Sub End Class End Class Sub Main() Dim OuterClassInstance As New OuterClass OuterClassInstance.NestedClassInstance.GetParentX() End Sub ```

Original source