Initialisers
Initialisers are new language contructs which allow Objects and Collections to
be created and initialised in a neat and efficient way.
Object Initialisers
Using the Book class above you would traditionally create a Book instance and
provide values as follows:
Book book = new Book();
book.Title = "The Dice Man";
book.Author = "Luke Rhinehart";
book.Publisher = "Harper Collins";
book.ISBN = "0006513905";
Object Initialiser syntax allows you to condense the above into a single
statement:
Book book = new Book { Title = "The Dice Man", Author = "Luke Rhinehart",
Publisher = "Harper Collins", ISBN = "0006513905" };
The syntax even works for complex nested objects. For example, if the Publisher
property was of type PubDetail (instead of string) with properties: Name and
Location it could be initialised as follows:
Book book = new Book {
Title = "The Dice Man",
Author = "Luke Rhinehart",
Publisher = new PubDetail {
Name = "Harper Collins",
Location = "New York"
}
ISBN = "0006513905"
};
Collection Initialisers
The generic collection classes can also be made easier to work with using the
new initialisation syntax. The first level optimisation of code to initalise a
list of books would be:
List<Book> books = new List<Book>();
books.Add( new Book { Title = "The Dice Man", Author = "Luke Rhinehart",
Publisher = "Harper Collins", ISBN = "0006513905" } );
books.Add( new Book { Title = "The Life of Pi", Author = "Yann Martel",
Publisher = "Canongate", ISBN = "184195392X" } );
books.Add( new Book { Title = "Vernon God Little", Author = "DBC Pierre",
Publisher = "Faber & Faber", ISBN = "0571215165" } );
However, the new syntax allows us to cut down the code even more by folding the
individual object initialisers into the constructor for the list:
List<Book> books = new List<Book> {
new Book { Title = "The Dice Man", Author = "Luke Rhinehart",
Publisher = "Harper Collins", ISBN = "0006513905" },
new Book { Title = "The Life of Pi", Author = "Yann Martel",
Publisher = "Canongate", ISBN = "184195392X" },
new Book { Title = "Vernon God Little", Author = "DBC Pierre",
Publisher = "Faber & Faber", ISBN = "0571215165" }
};