15.02.2015 Views

C# 4 and .NET 4

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

lists ❘ 231<br />

{<br />

if (action == null) throw new ArgumentNullException("action");<br />

}<br />

foreach (T item in items)<br />

{<br />

action(item);<br />

}<br />

}<br />

//...<br />

For passing a method with ForEach , Action < T > is declared as a delegate that defi nes a method with a void<br />

return type <strong>and</strong> parameter T:<br />

public delegate void Action < T > (T obj);<br />

With a list of Racer items, the h<strong>and</strong>ler for the ForEach() method must be declared with a Racer object as<br />

parameter <strong>and</strong> a void return type:<br />

public void ActionH<strong>and</strong>ler(Racer obj);<br />

Because one overload of the Console.WriteLine() method accepts Object as parameter, you can pass<br />

the address of this method to the ForEach() method, <strong>and</strong> every racer of the collection is written to the<br />

console:<br />

racers.ForEach(Console.WriteLine);<br />

You can also write a Lambda expression that accepts a Racer object as parameter <strong>and</strong> does the Console.<br />

WriteLine() with the implementation. Here, the format A is used with the ToString() method of the<br />

IFormattable interface to display all information about the racer:<br />

racers.ForEach(r = > Console.WriteLine("{0:A}", r));<br />

Lambda expressions are explained in Chapter 8, “ Delegates, Lambdas, <strong>and</strong> Events.”<br />

removing elements<br />

You can remove elements by index or pass the item that should be removed. Here, the fourth element is<br />

removed by passing 3 to RemoveAt() :<br />

racers.RemoveAt(3);<br />

You can also directly pass a Racer object to the Remove() method to remove this element. Removing<br />

by index is faster, because here the collection must be searched for the item to remove. The Remove()<br />

method fi rst searches in the collection to get the index of the item with the IndexOf() method, <strong>and</strong><br />

then uses the index to remove the item. IndexOf() fi rst checks if the item type implements the interface<br />

IEquatable < T > . If it does, the Equals() method of this interface is invoked to fi nd the item in the<br />

collection that is the same as the one passed to the method. If this interface is not implemented,<br />

the Equals() method of the Object class is used to compare the items. The default implementation<br />

of the Equals() method in the Object class does a bitwise compare with value types, but compares<br />

only references with reference types.<br />

Chapter 7, “ Operators <strong>and</strong> Casts, ” explains how you can override the Equals()<br />

method.<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!