Understanding Lambda Expressions


Lambda expression are nothing more than a concise way to author anonymous methods and ultimately simplify how you work with the .NET delegate type.


System.Predicate<T> delegate type can point to any method returning a bool and takes a single type parameter as the only input parameter.


public delegate bool Predicate<T>(T obj);


First understand that lambda expressions can be used anywhere you would have used an anonymous method or a strongly typed delegate.


List<int> list = new List<int> { 20, 1, 4, 8, 44 };
// FindAll() using a traditional delegate syntax.
Predicate<int> callback = IsEvenNumber;
List<int> evenNumbers = list.FindAll(callback);
 
private static bool IsEvenNumber(int obj)
 {
     return obj % 2 == 0;
 }
 
// Now use anonymous method
List<int> evenNumbers = list.FindAll(delegate (int i)
 {
     return i % 2 == 0;
 });
 
// Now use lambda expressions
List<int> evenNumbers = list.FindAll(i => (i % 2) == 0);


In the compiler: ildasm.exe

Lambda expression would always be anonymous method.


Using static with Lambda Expressions


var outerVariable = 0;
Func<int, int, bool> DoWork = static (x, y) =>
 {
     // outerVariable++;
     return true;
 };
 
DoWork(3, 4);


Discards with Lambda Expressions

Input variables to lambda expression can be replaced with discards if the input variables are not needed.


var outerVariable = 0;
Func<int, int, bool> DoWork = (_,_) =>
 {
     outerVariable++;
     return true;
 };
DoWork(0,0);
 

Lambdas and Expression-Bodied Members

If you have a method or property that consists of exactly a single line of code in the implementation, you are not required to define a scope via curly bracket! You can instead leverage the lambda operator and write an expression-bodied member.


In C# 7, you can also sue this syntax for class constructors, finalizers, and get and set accessors on property members.


From this

public class SimpleMath
 {
     public int Add(int x, int y)
     {
         return x + y;
     }
     public void PrintSum(int x, int y)
     {
         Console.WriteLine(x+" "+y);
     }
 }


To this:

public int Add(int x, int y) => x + y;
public void PrintSum(int x, int y) => Console.WriteLine(x+" "+y);