9.7. Using Lambda Expressions
Problem
There is a feature in C# 3.0 called lambda expressions. While lambda expressions can be viewed as syntactic sugar for making anonymous method definition less difficult, you want to understand all of the different ways that they can be used to help you in your daily programming chores as well as understand the ramifications of those uses.
Solution
Lambda expressions can be implemented by the compiler from methods created by the developer. There are two orthogonal characteristics that lambda expressions may have:
Parameter lists may have explicit or implicit types.
Bodies may be expressions or statement blocks.
Let's start with the original way to use delegates. First, you would declare a delegate type, DoWork in this case, and then you would create an instance of it (as shown here in the WorkItOut method). Declaring the instance of the delegate requires that you specify a method to execute when the delegate is invoked, and here the DoWorkMethodImpl method has been connected. The delegate is invoked, and the text is written to the console via the DoWorkMethodImpl method:
class OldWay { // declare delegate delegate int DoWork(string work); // have a method to create an instance of and call the delegate public void WorkItOut( ) { // declare instance DoWork dw = new DoWork(DoWorkMethodImpl); // invoke delegate int i = dw("Do work the old way"); } // Have a method that the delegate is tied to with a matching signature // so that it is invoked when the delegate ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access