Define a Collection and Initialize Its Values

You can now define a collection class or an array and, at the same time, set the initial values in your object. This turns multiple lines of code calling simple add methods into a single line. This is especially useful if you have a list of items that your application works with and you need to both declare the list and initialize these values.

For example, you might need to define an array to contain the geographic locations for your sales office. You could define this array and initialize it as follows.

C#

string[] salesGeos = {"South", "Mid Atlantic", "Mid West"};

VB

Dim salesGeos() As String = {"South", "Mid Atlantic", "Mid West"}

You can use similar syntax to define and initialize a collection class, including those based on a generic. For example, the following defines a list of Employee objects and adds two new Employee classes to that list. Note that the Visual Basic code requires the From keyword.

C#

List<Employee> empList = new List<Employee>
  {new Employee("1234"), new Employee("3456")};

VB

Dim empList As New List(Of Employee) From _
  {New Employee("1234"), New Employee("3456")}

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

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