C# Async Lambda
Lambda expressions in LINQ typically act as a means of translating logic at run time to pass to the data source.
They also appear as a means of defining a value. Review lambda expression syntax below:
(input parameters) => expression or statement block
Review an example of its use below:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace TestLambda { class Example { delegate int del(int i); static void Main(string[] args) { del customDelegt = x => x * x; int w = customDelegt(3); Console.WriteLine(w); Console.ReadLine(); } } }
ASYNC
Lambda expressions also appear as instruments of asynchronous processing operations using the keyword async. Review an example below:
Func<Task<string>> getWordAsync = async() => “Hey!”;
QUERY OPERATION
These expressions also find use as a means of feeding logic to a query. Review an example below:
//Find the average of odd Fibonacci numbers using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace TestLambda { class Example { static void Main(string[] args) { int[] fiboNo = { 1, 1, 2, 3, 5, 8, 13, 21, 34 }; double avgValz = fiboNo.Where(no => no % 2 == 1).Average(); Console.WriteLine(avgValz); Console.ReadLine(); } } }
TYPE MANAGEMENT
The compiler generally infers type from specifications (declarations), however, in C#, the type inference often makes explicit specification unnecessary.
VARIABLE SCOPE
Variables initiated within a lambda expression are not intended to remain visible in an outer method; furthermore, captured variables cannot be collected by garbage collection until their referencing delegate reaches garbage collection state. Another rule of scope prevents return statements in lambda expressions from causing the return of an enclosing method.
STATEMENTS
Lambdas as statements consist of 2 or 3 statements, however, they are not employed in expression tree construction, and must include a return statement. Review syntax below:
(params) => {statements}
Review an example below:
using System.Collections.Generic; using System.Linq; using System.Text; using System.Linq.Expressions; namespace TestLambda { class Example { static void Main(string[] args) { int[] set = new[] { 3, 9, 5, 7, 1, 6, 8, 2, 5, 8 }; foreach (int i in set.Where( y => { if (y <= 3) return true; else if (y >= 7) return true; return false; } )) Console.WriteLine(i); Console.ReadLine(); } } }
KEY QUALITIES
When using lambda expressions, a few of their qualities have distinction:
- Lambda expressions can return values and obey parameters.
- Many ways to define parameters with lambda expressions exist.
- In single-statement lambdas, omit curly braces. In multiple-statement lambda expressions, employ braces and include a return value.
- Lambda expressions allow access to variables outside of the expression, but use this feature (known as closure) with caution.
- Lambda expressions do not permit unsafe code.