Home > OS >  How do I construct an "Add" routine for a custom object list?
How do I construct an "Add" routine for a custom object list?

Time:03-07

I feel really stupid asking this question, but here goes...

I'm trying to create a custom object in VB, that is itself a list (or collection, or "tuple" - I'm not sure what the difference between these is) of custom objects, and I need to create routines to add and remove these secondary objects to/from the larger custom object. So far, my code goes something like this:

Public Class parameterSet
    Friend _xParameter As String
    Public Property xParameter() As String
        Get
            Return _xParameter
        End Get
        Set(value As String)
            _xParameter = value
        End Set
    End Property
    Friend _yParameter As String
    Public Property yParameter() As String
        Get
            Return _yParameter
        End Get
        Set(value As String)
            _yParameter = value
        End Set
    End Property
    Friend _zParameter As String
    Public Property zParameter() As String
        Get
            Return _zParameter
        End Get
        Set(value As String)
            _zParameter = value
        End Set
    End Property
    Public Sub New(ByVal xParameter As String, ByVal yParameter As String, ByVal zParameter As String)
        _xParameter = xParameter
        _yParameter = yParameter
        _zParameter = zParameter
    End Sub
End Class
Public Class parameterCollection
    Friend _parameterCollection As New List(Of parameterSet)
    Friend Sub Add(xParameter As String, yParameter As String, zParameter As String)
        Throw New NotImplementedException()
    End Sub
End Class

What do I have to put in the Add routine to make this work?

CodePudding user response:

Your first class ought to look like this:

Public Class ParameterSet

    Public Property X As String
    Public Property Y As String
    Public Property Z As String

    Public Sub New(x As String, y As String, z As String)
        Me.X = x
        Me.Y = y
        Me.Z = z
    End Sub

End Class

Your second class ought to look like this:

Imports System.Collections.ObjectModel

Public Class ParameterSetCollection
    Inherits Collection(Of ParameterSet)

    Public Overloads Sub Add(x As String, y As String, z As String)
        Add(New ParameterSet(x, y, z))
    End Sub

End Class

You might even want to do this:

Imports System.Collections.ObjectModel

Public Class ParameterSetCollection
    Inherits Collection(Of ParameterSet)

    Public Overloads Function Add(x As String, y As String, z As String) As ParameterSet
        Dim item = New ParameterSet(x, y, z)

        Add(item)

        Return item
    End Function

End Class

The Collection(Of T) class already provides all the standard collection functionality and you can extend it as required.

  • Related