Share via


How to: Create an Add Extension Method Used by a Collection Initializer (Visual Basic)

When you use a collection initializer to create a collection, the Visual Basic compiler searches for an Add method of the collection type for which the parameters for the Add method match the types of the values in the collection initializer. This Add method is used to populate the collection with the values from the collection initializer.

If no matching Add method exists and you cannot modify the code for the collection, you can add an extension method called Add that takes the parameters that are required by the collection initializer. This is typically what you need to do when you use collection initializers for generic collections.

Example

The following example shows how to add an extension method to the generic List<T> type so that a collection initializer can be used to add objects of type Employee. The extension method enables you to use the shortened collection initializer syntax.

Public Class Employee
    Public Property Id() As Integer
    Public Property Name() As String
End Class
Imports System.Runtime.CompilerServices

Module Module1

    <Extension()>
    Sub Add(ByVal list As List(Of Employee), ByVal id As Integer,
                                             ByVal name As String)
        list.Add(New Employee With {.Id = id, .Name = name})
    End Sub

End Module
Sub Main()
    Dim employees = New List(Of Employee) From {{1, "Adams, Ellen"},
                                                {2, "Hamilton, James R."},
                                                {3, "Ihrig, Ryan"}}
End Sub

See Also

Tasks

How to: Create a Collection Used by a Collection Initializer (Visual Basic)

Concepts

Collection Initializers Overview (Visual Basic)