liveBook · Manning

Lambda

As explained in .NET in Action, Second Edition

An anonymous method is a C# method implementation declared without a named method declaration and commonly represented as a delegate or function value.

A lambda creates an anonymous function: a function whose name is unnecessary. Lambdas are useful for one-off callbacks, such as handling command-line parsing failures, without adding a named method. section 2.8

C# has two lambda forms:

  • An expression lambda uses a single expression or statement and needs no braces. section 2.8
  • A statement lambda uses multiple statements inside braces. section 2.8
  • Lambdas can be assigned to Action or Func delegates. Their generic arguments let the compiler infer parameter and return types. section 2.8
Listing 2.19 Examples of lambda expression types
Action<int, int> a1 = (x, y) => WriteLine(x + "," + y);    #1
Action<string, string> a2 = (left, right) =>               #2
{
  if (left == right)
  {
    WriteLine("Matches!");
  }
  else
  {
    WriteLine("Does not match!");
  }
};
  
Func<int, int, int> multiply = (x, y) => x * y;            #3
Func<IEnumerable<int>, int> sum =                          #4
numbers =>                                                 #5
{
  int running = 0;
  foreach (int num in numbers)
  {
    running += num;
  }
  
  return running;
};
  
var parse = (string s) => int.Parse(s);                    #6

Examples range from concise expression lambdas to multi-statement bodies, including callbacks that print, compare strings, multiply, sum, and parse. section 2.8

How .NET in Action, Second Edition covers it

How deep it goes
Defines expression and statement lambdas, demonstrates delegate assignment and type inference, but does not detail generated runtime representation.
Examples
Compares named handlers with lambdas and demonstrates printing, string comparison, multiplication, summation, and parsing.
What you can do after
Apply Action and Func delegates to write inline callbacks and expression- or statement-bodied functions.
How it connects
Connects anonymous functions with delegates, Action, Func, and command-line parsing callbacks.

Also explained in

Compare how 18 books explain lambda →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of .NET in Action, Second Edition. The section links point to the parts of the book it draws on.