11.07.2015 Views

Beginning C# 2008-from Novice-to-professional - A2Z Dotnet

Beginning C# 2008-from Novice-to-professional - A2Z Dotnet

Beginning C# 2008-from Novice-to-professional - A2Z Dotnet

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

CHAPTER 9 ■ LEARNING ABOUT LISTS, DELEGATES, AND LAMBDA EXPRESSIONS 241A delegate and interface share the same role, in that they are types without implementationsand are used <strong>to</strong> build components. An interface can have multiple methods and properties.A delegate is a method declaration and can define only the parameters and return types. Thepurpose of delegates is <strong>to</strong> be able <strong>to</strong> define a generic method-calling mechanism without needing<strong>to</strong> add the baggage of implementing an interface.The approach used in the delegate solution <strong>to</strong> the problem presented in the previous sectionis <strong>to</strong> define a chunk of functionality that performs the iteration, called an itera<strong>to</strong>r. Andthen <strong>to</strong> do something with the iteration, another chunk of functionality is integrated via a delegate.The result is that you have two separate pieces of functionality that are integrated usinga component methodology.Following is the complete rewritten foreach code that uses delegates.public delegate void ProcessValue(int value);public static class Extensions {public static void Iterate(this ICollection collection,ProcessValue cb) {foreach (int element in collection) {cb(element);}}}static class Tests {static int _runningTotal;static void ProcessRunningTotal(int value) {_runningTotal += value;}static int _maxValue;static void ProcessMaximumValue(int value) {if (value > _maxValue) {_maxValue = value;}}static void DoRunningTotalAndMaximum() {List lst = new List { 1, 2, 3, 4 };_runningTotal = 0;lst.Iterate(new ProcessValue(ProcessRunningTotal));Console.WriteLine("Running <strong>to</strong>tal is (" + _runningTotal + ")");}_maxValue = int.MinValue;lst.Iterate(new ProcessValue(ProcessMaximumValue));Console.WriteLine("Maximum value is (" + _maxValue + ")");

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

Saved successfully!

Ooh no, something went wrong!