Posts Tip: Read Only Property via Interface - Read Write via Class.

Tip: Read Only Property via Interface - Read Write via Class.

Question: How do I implement a read only property of an interface implementation but allow the same property to be read write when accessing the property through the class directly?

Public Interface IInterface
ReadOnly Property AProperty() As Integer

Class AClass
Implements IInterface

  ' Will be used by the interface... and will not be visible
  ' when using the class directly.
Private ReadOnly Property _AProperty() As Integer _
Implements IInterface.AProperty
Return AProperty
End Get
End Property

  ' Will not be visible when using the interface.. and will be
  ' used when access the class directly.
Public Property AProperty() As Integer
Return 0 ' Whatever the real implementation should be.
End Get
Set(ByVal value As Integer)
' Set your value here...
End Set
End Property



Dim iDemo As IInterface = New AClass
' Won't work, no set on the interface.
' This is because internally it is using the _AProperty property -
' the one that follows the implementation for AProperty of IInterface.
iDemo.AProperty = "Setting the value"

cDemo As AClass = New AClass
' Works, it's an instance of the class itself.
' This is because it is now using the actual AProperty property
' of the AClass class. _AProperty is not visible since it's private
' using this scope.
cDemo.AProperty = "Setting the value"

Now wait a minute!  I have two properties!?!?  Why is this?

Since VB.NET requires you to specify what property will be used as the implementation (notice it doesn't have to have the same name) and it requires that the property implementing the interface item to match exactly, you must specify a hidden property to handle the implementation version if you want to create a read write version.  You then create a public read write property that allows you to access the property when using the class directly.

This also gives you the ability to specify an implementation version of the property while completely hiding it when accessing the class directly.

This post is licensed under CC BY 4.0 by the author.