[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Initialize arrays, lists, and class instances in C#

initialize arrays and lists

You can initialize objects that implement IEnumerable such as arrays and lists by specifying items inside brackets and separated by commas. For example, the following code initializes an array of strings.

// Arrays implement IEnumerable so this syntax works. string[] fruits = { "Apple", "Banana", "Cherry" }; lstFruits.DataSource = fruits; // Lists implement IEnumerable so this syntax works. List cookies = new List() { "Chocolate Chip", "Snickerdoodle", "Peanut Butter" }; lstCookies.DataSource = cookies;

This code uses the array initialization syntax to initialize an array of strings. It then sets the lstFruits ListBox's DataSource property equal to the array to display the strings.

The code then uses similar code to initialize a List<string> and displays its values.

A class doesn't (usually) implement IEnumerable so you cannot initialize a new instance by simply including property values inside brackets. However, you can use a special object initialization syntax that is fairly similar. The only difference is that you must include the name of the properties that you are setting as shown in the following code.

new Person() { FirstName="Simon", LastName="Green" }

The example program uses the following cod to initialize an array of Person objects and display its contents.

Person[] people = { new Person() { FirstName="Simon", LastName="Green" }, new Person() { FirstName="Terry", LastName="Pratchett" }, new Person() { FirstName="Eowin", LastName="Colfer" }, }; lstPeople.DataSource = people;

Download the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.