Lambda Expressions in C# From Beginner To Expert
Jaliya Udagedara
What are we going to discuss today?Introduction to Lambda ExpressionsWhat are Delegates in C#The Evolution of Delegates in C#Demo 1 - Delegates and Named Methods, Anonymous MethodsLambdas as Generic Delegates
ActionFuncPredicate
Lambdas as Callable EntitiesLambda Expression Execution
Lambdas as CallbacksDemo 2 – Lambda Expressions
Introduction to Lambda ExpressionsIntroduced with .NET 3.5/C# 3.0Supersede anonymous methods
Anonymous methods enable you to omit the parameter listUnnamed, inline functionsUsed wherever delegates are required
(input parameters) => expression
Expression Lambdas(input parameters) => expression
Statement Lambdas(input parameters) => {statement;}
Async Lambdas(input parameters) => async
{statement;}
What are Delegates in C#Delegates are like C++ function pointersMakes it possible to treat methods as entities.
Assign to variablesPass as parameters
Delegates can be chained together; for example, multiple methods can be called on a single event.Does delegates are exactly same as C++ function pointers?Does methods has to match the delegate type exactly?
What are Delegates in C# contd.Delegates are like C++ function pointers but are type safe.Variance in Delegates
Covariance permits a method to have return type that is More derived than that defined in the delegate
Contravariance permits a method that has parameter types that are less derived than those in the delegate type.
The Evolution of Delegates in C#C# 1.0 the only way to declare a delegate was to use named methods.C# 2.0 introduced anonymous methods as a way to write unnamed inline statement blocks that can be executed in a delegate invocation.C# 3.0 introduced lambda expressions, which are similar in concept to anonymous methods but more expressive and concise.
Classic Delegate Example
btnHelloWorld.Click += new
EventHandler(btnHelloWorld_Click);
Anonymous MethodsbtnHelloWorld.Click += delegate(System.Object sender, System.EventArgs e) { … };
Lambda ExpressionsbtnHelloWorld.Click += (sender, e) => { ... };
Demo• Delegates and Named
Methods• Anonymous Methods
Lambdas as Generic DelegatesGeneric delegates were new in .NET 2.0Action DelegatesFunc DelegatesPredicate Delegates
Action DelegateZero, one or more input parameters, and does not return anything.Takes up to 16 parametersArray.ForEach method and List.ForEachPerform an action on each element of the array or list
Action<int,int,string>
Func DelegateZero, one or more input parameters, and returns a valueTakes up to 16 parametersList.First
Func<int,int,string>
Predicate DelegateEncapsulates a method that evaluates to True or FalseTakes one parameterList.Find
Func<int>
Lambdas as Callable EntitiesLambda expressions can be assigned to a delegate variableLambda expression is executed when the delegate is executed Func<int, string> myFunc = x => { return String.Format("{0}*{0} is {1}", x, x * x); }; Console.WriteLine(myFunc(4));
Lambda Expression ExecutionLambda expressions are executed when they are called, not when they are constructedVariable value used is the value at execution time
Example: Local Variablesint y = 0;Func<int, string> myFunc = x => (x + y).ToString();y = 10;Console.WriteLine(myFunc(5));
Answer?
Lambdas as CallbacksCallback
“Executable code that is passed as an argument to other code”Passes a function to a function static void DoWork() { CallBack(s => Console.WriteLine(s)); }
static void CallBack(Action<string> MyAction) { MyAction("Completed"); }
Demo• Lambdas as Generic Delegates• Lambdas as Callable Entities• Lambdas as Callbacks
Thank You!http://www.jaliyaudagedara.blogspot.com/