Working with Collection Initializers

Visual Basic 2010 introduces a new language feature known as collection initializers. Basically this feature works like the object initializers, except that it is specific for instantiating and populating collections inline. To take advantage of collection initializers, you need to use the From reserved keyword enclosing items within brackets, as demonstrated in the following code:

'With primitive types
Dim listOfIntegers As New List(Of Integer) From {1, 2, 3, 4}

The preceding code produces the same result as the following:

image

You can easily understand how collection initializers enable writing less code that’s more clear. This feature can also be used with any other .NET type. The following code snippet shows how you can instantiate inline a List(Of Person):

image

The code also shows how you can take advantage of implicit line continuation if you have long lines for initializations. When you have an instance of the new collection, you can normally manipulate it. Of course, this feature works with any other collection type.

Non Generic Collections

Collection initializers are also supported by nongeneric collections using the same syntax.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.29.139