How to: Create an Add Extension Method Used by a Collection Initializer

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.

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.

' Create an array of type String().
Dim winterMonths = {"December", "January", "February"}

' Create an array of type Integer()
Dim numbers = {1, 2, 3, 4, 5}

' Create a list of menu options. (Requires an extension method
' named Add for List(Of MenuOption)
Dim menuOptions = New List(Of MenuOption) From {{1, "Home"},
                                                {2, "Products"},
                                                {3, "News"},
                                                {4, "Contact Us"}}
Imports System.Runtime.CompilerServices

Module Module1

    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
© 2015 Microsoft