Best access-modifiers questions in January 2011

Nested class Access methods for Properties in .NET

4 votes

Hi, I am trying to figure out the best approach for setting and getting properties in a nested class I am creating.

I have a class, Car which has a nested class ControlPanel and want to make the properties of the Control Panel only accessible to the Car and Control Panel class.

(ie: not within the assembly or namespace and not within the application the class library will be going to be used)... I have changed the class access properties to friend, protected friend, private, public, but any combination is not matching my expected results.

I want to change the properties in the Drive() Sub of a class as shown below.

Any thoughts?

 Public Class Car

    Dim cp As New ControlPanel

    Public Class ControlPanel
      Private _Speedometer As Integer = 0
      Private _Odometer As Integer = 0

      Public Property Speedometer() As Integer
        Get
            Return _Speedometer
        End Get
        Protected Set(ByVal value As Integer)
            _Speedometer = value
        End Set
      End Property

      Public Property Odometer() As Integer
        Get
            Return _Odometer
        End Get
        Protected Set(ByVal value As Integer)
            _Odometer = value
        End Set
     End Property

    End Class

   Public Sub Drive()

        cp.Odometer = 76323
        co.Speedometer = 86

   End Sub

End Class

You can do it like this:

Public Class Car

  Private Interface IControlPanel
    Property Odometer As Integer
    Property Speedometer As Integer
  End Interface

  Public Class ControlPanel
    Implements IControlPanel
    Public ReadOnly Property Odometer As Integer
      Get
        Return CType(Me, IControlPanel).Odometer
      End Get
    End Property
    Public ReadOnly Property Speedometer As Integer
      Get
        Return CType(Me, IControlPanel).Speedometer
      End Get
    End Property
    Private Property IControlPanel_Odometer As Integer Implements IControlPanel.Odometer
    Private Property IControlPanel_Speedometer As Integer Implements IControlPanel.Speedometer
  End Class

  Dim cp As IControlPanel = New ControlPanel()

  Public Sub Drive()
    cp.Odometer = 76323
    cp.Speedometer = 86 
  End Sub

End Class

It uses a private interface nested in the Car class with privately implemented and aliased members in ControlPanel. This way, only Car can access the interface members.