Free mag vol1 | Page 437

CHAPTER 10  DELEGATES, EVENTS, AND LAMBDA EXPRESSIONS delegate for your project, other times the exact name of the delegate is irrelevant. In many cases, you simply want “some delegate” that takes a set of arguments and possibly has a return value other than void. In these cases, you can make use of the framework’s built-in Action<> and Func<> delegates. To illustrate their usefulness, create a new Console Application project type named ActionAndFuncDelegates. The generic Action<> delegate is defined in the System namespaces of mscorlib.dll and System.Core.dll assemblies. You can use this generic delegate to “point to” a method that takes up to 16 arguments (that ought to be enough!) and returns void. Now recall, because Action<> is a generic delegate, you will need to specify the underlying types of each parameter as well. Update your Program class to define a new static method that takes three (or so) unique parameters, for example: // This is a target for the Action<> delegate. static void DisplayMessage(string msg, ConsoleColor txtColor, int printCount) { // Set color of console text. ConsoleColor previous = Console.ForegroundColor; Console.ForegroundColor = txtColor; for (int i = 0; i < printCount; i++) { Console.WriteLine(msg); } // Restore color. Console.ForegroundColor = previous; } Now, rather than building a custom delegate manually to pass the program’s flow to the DisplayMessage() method, we can use the out-of-the-box Action<> delegate, as so: static void Main(string[] args) { Console.WriteLine("***** Fun with Action and Func *****"); // Use the Action<> delegate to point to DisplayMessage. Action actionTarget = new Action(DisplayMessage); actionTarget("Action Message!", ConsoleColor.Yellow, 5); } Console.ReadLine(); As you can see, using the Action<> delegate saves you the bother of defining a custom delegate. However, recall that the Action<> delegate can point only to methods that take a void return value. If you want to point to a method that does have a return value (and don’t want to bother writing the custom delegate yourself), you can use Func<>. The generic Func<> delegate can point to methods that (like Action<>) take up to 16 parameters and a custom return value. To illustrate, add the following new method to the Program class: // Target for the Func<> delegate. static int Add(int x, int y) { 376