Object and Collection Initializers


C# 1.0 offered an easy syntax to initialize arrays:

 int[] arr = {1, 2, 3, 4};

This was the short-term notation compared to:

 int[] arr = new int[4]; arr[0] = 1; arr[1] = 2; arr[2] = 3; arr[3] = 4;

With C# 3.0, the same is possible with collection classes. You can use curly brackets to initialize the collection with the instantiation:

  List<string> arr = new List<string> { "Nino", "Alberto", "Juan", "Mike", "Phil" }; 

The new syntax works with every type that implements the interface ICollection<T>. The compiler converts the shorthand notation to invoke the Add() method that is defined with the ICollection<T> interface for every element in the collection initializer list.

  List<string> arr = new List<string>(); arr.Add("Nino"); arr.Add("Alberto"); arr.Add("Juan"); arr.Add("Mike"); arr.Add("Phil"); 

This shorthand also exists for objects: object initializers. With object initializers, you can assign values to properties by assigning values to property names inside curly brackets:

  Racer r = new Racer {Firstname = "Nino", Lastname="Farina"}; 

The compiler creates a new object and sets the properties of the object as defined with the object initializer:

  Racer r = new Racer(); r.Firstname = "Nino"; r.Lastname = "Farina"; 

Tip 

For attributes, property initializers have existed since C# 1.0.

You can combine collection with object initializers; of course, you can use object initializers within collection initializers. Here, it is also not necessary to use new Racer in the code, as the element type is already defined by the collection. You can add a new Racer inside the object initialization of collection initializers if required.

  List<Racer> racers = new List<Racer>       {          {Firstname="Nino", Lastname="Farina"},          {Firstname="Alberto", Lastname="Ascari"}       }; foreach (Racer r in racers) {    Console.WriteLine(r); } 

Running this code invokes the ToString() method of the Racer class and produces this output:

 Nino Farina Alberto Ascari




Professional C# 2005 with .NET 3.0
Professional C# 2005 with .NET 3.0
ISBN: 470124725
EAN: N/A
Year: 2007
Pages: 427

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net