Implementing and Overriding Read Only Properties

Ok enough crazy posts about divine design beings shining down on me from up on high. That’s what too much caffeine on an empty stomach does to a person!

So I’m beginning to hate VB.NET. Yup. There, I said it.

I was trying to create a read only interface to a Part object.

Public Interface IReadOnlyPart
    ReadOnly Property PartNumber() As String
End Interface

And Have a Part Class Implement that Interface like this:

Public Class Part
    Implements IReadOnlyPart
    Public Property PartNumber As String _
        Implements IReadOnlyPart.PartNumber()
    Etc.

That doesn’t work in VB. You can’t inherit a readonly property from an interface and then make it read/write. Grr! I’m told you can do this in C#, but I haven’t confirmed this. I posted an inquiry to microsoft.public.dotnet.languages.vb and got some great responses. This is the proposed solution by Steve Gerrard which, while perverse, works wonderfully.

Public Class Class1
    Implements IReadOnlyPart

    Private PartNum As String

    Private ReadOnly Property Dummy() As String _
        Implements IReadOnlyPart.PartNumber
        Get
            Dummy = PartNum
        End Get
    End Property

    Public Property PartNumber() As String
        Get
            PartNumber = PartNum ' or Dummy
        End Get
        Set(ByVal Value As String)
            PartNum = Value
        End Set
    End Property

End Class

Sample test code:

Dim o As Class1 = New Class1
Dim p As IReadOnlyPart = o

o.PartNumber = "test 001"
Debug.WriteLine("Class1: " + o.PartNumber)
Debug.WriteLine("IReadOnlyPart: " + p.PartNumber)

I never would have figured that out. Always ask for help when in over your head. I’ve got another post brewing on that same mailing list now about delegates.

Grr @ Delegates! So sexy, but so pointy.

Comments are closed.