Lambda Syntax - mcbride-clint/DeveloperCurriculum GitHub Wiki

Lambda syntax, either Lambda Expressions or Lambda Statements, are a tool to easily create anonymous functions. The => is the lambda declaration operator.

  • Expression lambda that has an expression as its body:
(input-parameters) => expression
  • Statement lambda that has a statement block as its body:
(input-parameters) => { <sequence-of-statements> }

Common Uses

Linq

Most commonly seen in Linq Statements like below. The Linq Where method is expecting a func<T, bool>. That is a function that has one input parameter of T, in this case User, and returns a bool.

 // Get User List
List<User> users = GetAllUsers();

// Narrow to Only Users with FirstName "John"
var johns = users.Where(u => u.FirstName == "John");

Same as providing a method directly:

private function IsNamedJohn(User u) {
  return u.FirstName == "John";
}

...

 // Get User List
List<User> users = GetAllUsers();

// Narrow to Only Users with FirstName "John"
var johns = users.Where(IsNamedJohn);

Properties

Lambdas can be used to create read-only properties that behave almost like parameter-less methods. Every time the property is called then the lambda will be executed again so be mindful of putting intensive operations behind lambda properties.

public class User {
  public FirstName { get; set; }
  public Age { get; set; }
  public bool CanDrive => { return Age > 16; }
}

See Also

⚠️ **GitHub.com Fallback** ⚠️