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.

8Delegates, lambdas, <strong>and</strong> events<br />

WhaT ’ s in This ChaPTer<br />

➤<br />

➤<br />

➤<br />

Delegates<br />

Lambda expressions<br />

Events<br />

Delegates are the .<strong>NET</strong> version of addresses to methods. Compare this to C++, where function<br />

pointers are nothing more than a pointer to a memory location that are not type - safe. You have<br />

no idea what a pointer is really pointing to, <strong>and</strong> items such as parameters <strong>and</strong> return types are not<br />

known. This is completely different with .<strong>NET</strong>; delegates are type - safe classes that defi ne the return<br />

types <strong>and</strong> types of parameters. The delegate class not only contains a reference to a method, but can<br />

hold references to multiple methods.<br />

Lambda expressions are directly related to delegates. When the parameter is a delegate type, you can<br />

use a Lambda expression to implement a method that ’ s referenced from the delegate.<br />

This chapter teaches you the basics of delegates <strong>and</strong> Lambda expressions, <strong>and</strong> shows you how to<br />

implement methods called by delegates with Lambda expressions. It also demonstrates how .<strong>NET</strong><br />

uses delegates as the means of implementing events.<br />

delegaTes<br />

Delegates exist for situations in which you want to pass methods around to other methods. To see<br />

what that means, consider this line of code:<br />

int i = int.Parse("99");<br />

You are so used to passing data to methods as parameters, as in this example, that you don ’ t<br />

consciously think about it, <strong>and</strong> for this reason the idea of passing methods around instead of<br />

data might sound a little strange. However, there are cases in which you have a method that does<br />

something, <strong>and</strong> rather than operating on data, the method might need to do something that involves<br />

invoking another method. To complicate things further, you do not know at compile time what this<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!