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 = 
lstFruits.DataSource = fruits;

// Lists implement IEnumerable so this syntax works.
List cookies = new List() 
    "Chocolate Chip", 
    "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;

See also:

Download Example   Follow me on Twitter   RSS feed

This entry was posted in arrays, classes, lists, OOP and tagged , , , , , , , , , , , , , . Bookmark the permalink.