Chad
Chad

Reputation: 24679

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

Upvotes: 0

Views: 128

Answers (2)

Hand-E-Food
Hand-E-Food

Reputation: 12794

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.

Upvotes: 1

alexn
alexn

Reputation: 58952

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

PhoneCollection.AddRange(phoneNumberArray)

Upvotes: 0

Related Questions