Initialize arrays, lists, and class instances in C#
You can initialize objects that implement IEnumerable such as arrays and lists by specifying items inside brackets and separated by commas. The following code initializes an array of strings and then a List<string>. It uses them as DataSources for two ListBoxes.
// Arrays implement IEnumerable so this syntax works.A class doesn't (usually) implement IEnumerable so you cannot initialize a new instance by simply including property values inside brackets, but 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.
string[] fruits =
{
"Apple",
"Banana",
"Cherry"
};
lstFruits.DataSource = fruits;
// Lists implement IEnumerable so this syntax works.
List<string> cookies = new List<string>()
{
"Chocolate Chip",
"Snickerdoodle",
"Peanut Butter"
};
lstCookies.DataSource = cookies;
// Classes such as Person don't implement IEnumerableSee also:
// so you cannot simply list the property values inside
// brackets. Instead use this syntax.
Person[] people =
{
new Person() { FirstName="Simon", LastName="Green" },
new Person() { FirstName="Terry", LastName="Pratchett" },
new Person() { FirstName="Eowin", LastName="Colfer" },
};
lstPeople.DataSource = people;
- Give a class auto implemented properties and initializing constructors in C#
- Override a class's ToString method to allow controls such as ListBox to display objects in C#


Comments