TAGS :Viewed: 9 - Published at: a few seconds ago

[ .NET Object initializers question ]

I'd like to have a convenient way to add Phone objects to a Phone collection. Is there some sort of object Initializer syntax that I can use to avoid the following custom routine?

I am using .NET 3.5

 Private Function PhoneNumbersToCollection(ByVal ParamArray phoneNumberArray() As TelephoneNumberType) As TelephoneNumberCollection

        Dim PhoneCollection As New TelephoneNumberCollection

        For Each phoneNumber As TelephoneNumberType In phoneNumberArray
            If phoneNumber IsNot Nothing Then
                PhoneCollection.Add(phoneNumber)
            End If
        Next

        Return PhoneCollection

    End Function

EDIT:

Public Class TelephoneNumberCollection 
   Inherits System.Collections.ObjectModel.Collection(Of TelephoneNumberType)

Answer 1


I generally inherit List(Of T) and duplicate it's constructors. The third one will do what you're after. If you want to exclude Nothing elements, you can rewrite the constructor.

Class TelephoneNumberCollection
    Inherits List(Of TelephoneNumberType)

    Public Sub New()
    End Sub

    Public Sub New(capacity As Integer)
        MyBase.New(capacity)
    End Sub

    Public Sub New(collection As IEnumerable(Of TelephoneNumberType))
        MyBase.New(collection)
    End Sub
End Class

You're not inheriting an List, but it would take minimal effort to rewrite those constructors in your TelephoneNumberCollection class.

EDIT: That was a stupid mistake I made. IList is not a class, List is.

Answer 2


If TelephoneNumberCollection implements IList of TelephoneNumberType, you can use AddRange:

PhoneCollection.AddRange(phoneNumberArray)