Tim
Tim

Reputation: 2892

VB.Net - Using a subclass in a class

Trying to convert some VBA code to VB.Net and getting hung up on some class issues. I have a main class: clsComputer. It has a subclass: clsHardDrive. Since a computer can have more than 1 hard drive, it's Get and Set properties look like this in clsComputer:

Private pHardDrive(8) As clsHardDrive

Public Property Get HardDrive(index As Integer) As clsHardDrive
    If pHardDrive(index) Is Nothing Then Set pHardDrive(index) = New clsHardDrive
    Set HardDrive = pHardDrive(index)
End Property
Public Property Set HardDrive(index As Integer, value As clsHardDrive)
    pHardDrive(index) = value
End Property

This allows me to do something like this in code:

objComp.HardDrive(0).Size = "500"
objComp.HardDrive(1).Size = "1000"

However, I don't know how to convert this to VB.Net. I tried this:

Property HardDrive As HDD
    Get (ByVal index As Integer)
        Return pHardDrive(index)
    End Get
    Set (ByVal index As Integer, value As HDD)          
        pHardDrive(index) = value
    End Set
End Property

But it gives a compile error: Property without a 'ReadOnly' or 'WriteOnly' specifier must provide both a 'Get' and a 'Set'. (BC30124)

Searching that error isn't very helpful: To correct this error make sure you include both a Get procedure and a Set procedure between the Property statement and the End Property statement. I have both Get and Set, and I think they are properly terminated. I've also searched for examples on using one class within another, but I didn't find anything useful.

How do I get the same functionality in VB.Net that I have in VBA? EG, how do I create the instances of HardDrive so that one computer object can have many hard drive objects?

Upvotes: 0

Views: 3296

Answers (1)

Cody Gray
Cody Gray

Reputation: 244722

Indexed properties still exist in VB.NET, just like classic COM-based VB.

You just have the syntax wrong. Indexed properties really just a special case of a parameterized property, so the index is taken as a parameter for the entire property, not the individual Get and Set statements.

Public Class Computer

    Private m_hardDrives(8) As HDD

    Public Property HardDrive(ByVal index As Integer) As HDD
        Get
            Return m_hardDrives(index)
        End Get
        Set(ByVal value As HDD)
            m_hardDrives(index) = value
        End Set
    End Property

End Class

Upvotes: 2

Related Questions