Lambda Expressions Basics


Anatomy of a Lambda Expression
// A simple Lambda expression
f => Console.WriteLine(f.ToString())
The “=>” thingy in the middle is the Lambda operator. This is what lets you know a Lambda is what is happening here. Let’s break the rest down into two parts: the left side and the right side. The left side represents a parameter list to be passed into the method. The right side represents the code the method will execute.
So you can think of this as a method defined like so:
// A faux method representing a Lambda
void Method (unknownType f)
{
    Console.WriteLine(f.ToString());
}


Where this gets confusing is that you really don’t see any type declarations, either for the parms or the return value. This is more Compiler Inference at work. In our example above, we specified that our Action generic was based on the Value Type of the Dictionary. The Compiler is able to look at the context of the Lambda Expression and simply infer that f is whatever type we specified on the Action parameter. You could write the details out, specifying the types, but not needing to is one of the major draws of Lambdas: the code is more compact and it “just works”.

Some odds and ends
There are a few items that I have to mention. First of all, Action also has a few multiple parameter options:
  • Action
  • Action
  • Action
We did not discuss sending multiple parameters to a Lambda. To do so, wrap them in parentheses, like so:
// Example from Microsoft
(x, y) => x == y
While Compiler Inference is at work here, it is not required. If you wish to specify types for readability you can:
// Example from Microsoft
(int x, int y) => x == y
Calling a Lambda with no parameters, such as Func is done with empty parentheses:
Func getSomething = () => "Something";
Console.WriteLine(getSomething());
Lambdas can access local variables:
string todo = "To Do";
Func getSomethingTodo = () => "Something " + todo;
Console.WriteLine(getSomethingTodo());

Comments