Post

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?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
Public Interface IInterface
  ReadOnly Property AProperty() As Integer
End Interface

Public  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
    Get
      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
    Get
      Return 0 ' Whatever the real implementation should be.
    End Get
    Set(ByVal value As Integer)
      ' Set your value here...
    End Set
  End Property

End Class
1
2
3
4
5
6
7
8
9
10
11
12
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"

Dim 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.