CHAPTER 10 DELEGATES, EVENTS, AND LAMBDA EXPRESSIONS
SimpleMath m = new SimpleMath();
m.SetMathHandler((msg, result) =>
{Console.WriteLine("Message: {0}, Result: {1}", msg, result);});
}
// This will execute the lambda expression.
m.Add(10, 10);
Console.ReadLine();
Here, we are leveraging type inference, as our two parameters have not been strongly typed for
simplicity. However, we could call SetMathHandler(), as follows:
m.SetMathHandler((string msg, int result) =>
{Console.WriteLine("Message: {0}, Result: {1}", msg, result);});
Finally, if you are using a lambda expression to interact with a delegate taking no parameters at all,
you may do so by supplying a pair of empty parentheses as the parameter. Thus, assuming you have
defined the following delegate type:
public delegate string VerySimpleDelegate();
you could handle the result of the invocation as follows:
// Prints "Enjoy your string!" to the console.
VerySimpleDelegate d = new VerySimpleDelegate( () => {return "Enjoy your string!";} );
Console.WriteLine(d());
Source Code The LambdaExpressionsMultipleParams project can be found under the Chapter 10 subdirectory.
Retrofitting the CarEvents Example Using Lambda Expressions
Given that the whole reason for lambda expressions is to provide a clean, concise manner to define an
anonymous method (and therefore indirectly a manner to simplify working with delegates), let’s retrofit
the PrimAndProperCarEvents project we created earlier in this chapter. Here is a simplified version of
that project’s Program class, which makes use of lambda expression syntax (rather than the raw
delegates) to hook into each event sent from the Car object:
static void Main(string[] args)
{
Console.WriteLine("***** More Fun with Lambdas *****\n");
// Make a car as usual.
Car c1 = new Car("SlugBug", 100, 10);
// Hook into events with lambdas!
c1.AboutToBlow += (sender, e) => { Console.WriteLine(e.msg);};
c1.Exploded += (sender, e) => { Console.WriteLine(e.msg); };
396