C# Easy · Lesson 1 · On the house

Lambdas and delegates

Func, Action, Predicate, lambda syntax, and passing behavior as values. Lesson 1 is free — on the house.

Lessons · C# Easy · Lesson 1 of 10 · On the house

Lambdas and delegates

Func, Action, Predicate, lambda syntax, and passing behavior as values.

Illustration for C#
Lesson 1 is on the house.

A lambda is an inline function: x => x * 2, (a, b) => a + b, or with a block body x => { var y = x + 1; return y; }.

Built-in delegate types describe signatures: Func<int, int> takes an int and returns an int (the last type is the return), Action<string> returns nothing, Predicate<T> returns bool.

Store and pass them like values: Func<int, int> square = x => x * x; Console.WriteLine(square(5));.

Lambdas capture outer variables by reference: changing the variable later changes what the lambda sees.

Method groups convert to delegates: names.ForEach(Console.WriteLine) passes the method directly.

Func + Action

Func<int, int> square = x => x * x;
Func<int, int, int> add = (a, b) => a + b;
Action<string> shout = s => Console.WriteLine(s.ToUpper());

Console.WriteLine(square(5));
Console.WriteLine(add(2, 3));
shout("hi");

int factor = 2;
Func<int, int> scale = x => x * factor;
factor = 10;
Console.WriteLine(scale(3));
Match this when you type.

Quiz

In Func<int, string>, what is the return type?

Quiz

Which delegate type returns nothing?

Quiz

What does scale(3) print after factor = 10?

Quiz

What does x => x * x define?

Check

Match the still for: Lambdas and delegates.

Open-book: the answers are on this page. Pass every quiz and check (5) to mark the lesson done. This visit: 0/5.