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;

See also:


Download Example   Follow me on Twitter   RSS feed




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

4 Responses to Initialize arrays, lists, and class instances in C#

  1. Pingback: Use auto implemented properties and initializing constructors in C#

  2. Pingback: Override ToString to allow controls such as ListBox to display objects in C# |

  3. Pingback: Give classes auto implemented properties and initializing constructors in C# |

  4. Pingback: Initialize two-dimensional arrays in C# - C# HelperC# Helper

Leave a Reply

Your email address will not be published. Required fields are marked *