Collection Initialization Syntax

Intertech Tutorials

C# Collection Initialization Syntax

Very closely related to the concept of object initialization syntax is collection initialization. This syntax makes it possible to populate a generic container (such as List<T>) or non-generic types (such as ArrayList) with items using a syntax that models that of a simple array.

Consider the following usage. As you examine the code, ponder the amount of code required under C# 2.0.


// C#
Init a List<T> of Rectangles
List<rectangle> myListOfRects = new List<rectangle>
{
new Rectangle {TopLeft = new Point { X = 10, Y = 10 },
    BottomRight = new Point { X = 200, Y = 200}},
new Rectangle {TopLeft = new Point { X = 2, Y = 2 },
    BottomRight = new Point { X = 100, Y = 100}},
new Rectangle {TopLeft = new Point { X = 5, Y = 5 },
    BottomRight = new Point { X = 90, Y = 75}}
};

Unfortunately, the current release of VB does not support using collection initialization syntax. Therefore, VB programmers will need to create the container and then call the Add() method for each type they wish to insert.


' VB
Sub Main()
' Make the container first.
Dim myListOfRectangles As New List(Of Rectangle)

' Add items via the Add() method.
myListOfRectangles.Add(New Rectangle With { _
.TopLeft = New Point With {.X = 10, .Y = 10}, _
.BottomRight = New Point With {.X = 200, .Y = 200}})
End Sub

Copyright (c) 2008-2013. Intertech, Inc. All Rights Reserved. This information is to be used exclusively as an online learning aid. Any attempts to copy, reproduce, or use for training is strictly prohibited.