15.02.2015 Views

C# 4 and .NET 4

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

lists ❘ 229<br />

Collection initializers are not refl ected within the IL code of the compiled assembly.<br />

The compiler converts the collection initializer to invoke the Add() method for every<br />

item from the initializer list.<br />

adding elements<br />

You can add elements to the list with the Add() method as shown. The generic instantiated type defi nes the<br />

parameter type of the Add() method.<br />

var intList = new List < int > ();<br />

intList.Add(1);<br />

intList.Add(2);<br />

var stringList = new List < string > ();<br />

stringList.Add("one");<br />

stringList.Add("two");<br />

The variable racers is defi ned as type List < Racer > . With the new operator, a new object of the same<br />

type is created. Because the class List < T > was instantiated with the concrete class Racer , now only Racer<br />

objects can be added with the Add() method. In the following sample code, fi ve Formula - 1 racers are created<br />

<strong>and</strong> added to the collection. The fi rst three are added using the collection initializer, <strong>and</strong> the last two<br />

are added by invoking the Add() method explicitly:<br />

var graham = new Racer(7, "Graham", "Hill", "UK", 14);<br />

var emerson = new Racer(13, "Emerson", "Fittipaldi", "Brazil", 14);<br />

var mario = new Racer(16, "Mario", "Andretti", "USA", 12);<br />

var racers = new List < Racer > (20) {graham, emerson, mario};<br />

racers.Add(new Racer(24, "Michael", "Schumacher", "Germany", 91));<br />

racers.Add(new Racer(27, "Mika", "Hakkinen", "Finl<strong>and</strong>", 20));<br />

code snippet ListSamples/Program.cs<br />

With the AddRange() method of the List < T > class, you can add multiple elements to the collection at once.<br />

The method AddRange() accepts an object of type IEnumerable < T > , so you can also pass an array<br />

as shown:<br />

racers.AddRange(new Racer[] {<br />

new Racer(14, "Niki", "Lauda", "Austria", 25),<br />

new Racer(21, "Alain", "Prost", "France", 51)});<br />

The collection initializer can be used only during declaration of the collection. The<br />

AddRange() method can be invoked after the collection is initialized.<br />

If you know some elements of the collection when instantiating the list, you can also pass any object<br />

that implements IEnumerable < T > to the constructor of the class. This is very similar to the AddRange()<br />

method:<br />

var racers =<br />

new List < Racer > (new Racer[] {<br />

new Racer(12, "Jochen", "Rindt", "Austria", 6),<br />

new Racer(22, "Ayrton", "Senna", "Brazil", 41) });<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!