13.07.2015 Views

C# in Depth

C# in Depth

C# in Depth

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

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

160 CHAPTER 5 Fast-tracked delegates5.6 Summary<strong>C#</strong> 2 has radically changed the ways <strong>in</strong> which delegates can be created, and <strong>in</strong> do<strong>in</strong>gso it’s opened up the framework to a more functional style of programm<strong>in</strong>g. Thereare more methods <strong>in</strong> .NET 2.0 that take delegates as parameters than there were <strong>in</strong>.NET 1.0/1.1, and this trend cont<strong>in</strong>ues <strong>in</strong> .NET 3.5. The List type is the bestexample of this, and is a good test-bed for check<strong>in</strong>g your skills at us<strong>in</strong>g anonymousmethods and captured variables. Programm<strong>in</strong>g <strong>in</strong> this way requires a slightly differentm<strong>in</strong>d-set—you must be able to take a step back and consider what the ultimateaim is, and whether it’s best expressed <strong>in</strong> the traditional <strong>C#</strong> manner, or whether afunctional approach makes th<strong>in</strong>gs clearer.All the changes to delegate handl<strong>in</strong>g are useful, but they do add complexity to thelanguage, particularly when it comes to captured variables. Closures are always tricky<strong>in</strong> terms of quite how the available environment is shared, and <strong>C#</strong> is no different <strong>in</strong>this respect. The reason they’ve lasted so long as an idea, however, is that they canmake code simpler to understand and more immediate. The balanc<strong>in</strong>g act betweencomplexity and simplicity is always a difficult one, and it’s worth not be<strong>in</strong>g too ambitiousto start with. As anonymous methods and captured variables become more common,we should all expect to get better at work<strong>in</strong>g with them and understand<strong>in</strong>g whatthey’ll do. They’re certa<strong>in</strong>ly not go<strong>in</strong>g away, and <strong>in</strong>deed LINQ encourages their useeven further.Anonymous methods aren’t the only change <strong>in</strong> <strong>C#</strong> 2 that <strong>in</strong>volves the compiler creat<strong>in</strong>gextra types beh<strong>in</strong>d the scenes, do<strong>in</strong>g devious th<strong>in</strong>gs with variables that appear tobe local. We’ll see a lot more of this <strong>in</strong> our next chapter, where the compiler effectivelybuilds a whole state mach<strong>in</strong>e for us <strong>in</strong> order to make it easier for the developerto implement iterators.Licensed to Rhona Hadida

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

Saved successfully!

Ooh no, something went wrong!