Monday, September 11, 2017

Lambda Expression

With Parameters

A method is a named block of code

public void DoSomething(parameters)
{
    code...
}

Lambda expression = unnamed block of code

They are easy to identify because they have a => in the statement to identify the lambda expression.

(parameters) => 
{
     code...
}

No Parameters

A method with NO parameters would look like this

public void DoSomething()
{
    code...
}

The lambda expression would look like

() => 
{
     code...
}


Behind the scenes

Lambda express = custom class and delegate

The compiler will create a class with an arbitrary name and a method with an arbitrary name and implemented with the same signature as the lambda expression.

Actions

You can think of Actions as pointers to methods.
An Action is an instance of a delegate.
When you see a signature for a method that requires a parameter that is of type Action what it is asking for is a lambda expression.

NOTE: To create an Action you can also use a method as shown below.
Action action = new Action(DoSomething());

Reference

Content is based on Pluralsight video called Introduction to Async and Parallel Programming in .NET 4 by Dr. Joe Hummel. 

No comments: