C# Refresh

Nonsultant
50.1K views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

Lambda expressions in C#

In this course are we going to work a lot with LINQ and one cornerstone of LINQ is lambda expressions (especially when using the method-syntax), which more or less is build on top of Lambda Calculus. Many places are lambda using the Greek symbol : λ .

Anonymous Methods

Lambda expressions is build upon the notion of anonymous method, these are methods which doesn’t contain any name and can be parsed around like parameters. Anonymous methods are defined using the delegate keyword and the user can assign this method to a variable of the delegate type.

Example of anonymous method

In this example is a delegate called MakeASoundDelegate, this allow for us to define the implementation of MakeASound and parse this around as a variable.

In some circumstances can delegates be used as an alternative to an interface.

Lambda expressions

As written previously is lambda expressions an evolution of anonymous methods, but there is some key differences:

  • Lambda expressions don't need to have a delegate variable
  • Lambda expressions must return a value
  • The result of a lambda expression is Func<inputs, output>

The => operator is called the "lambda operator", and is used when defining the expression.

Example

The previous example rewritten to use Lambda expressions instead

The definition of the Lambda expressions in the main method can compressed a bit to make the code easier to read:

void Main()
{
	var d = new Dog();
	Console.WriteLine($"{d.Specie} has {d.NumberOfLegs} legs");
	d.MakeASound(sound => { return $"The dog goes: {sound}"; });

	var h = new Human();
	Console.WriteLine($"{h.Specie} has {h.NumberOfLegs} legs");
	h.MakeASound(sound => {return $"The human goes: {sound}";});
}

Lambda expression with multiple parameters

It's possible to define lambda expressions with mulitple input parameters.

Open Source Your Knowledge: become a Contributor and help others learn. Create New Content