×

c# · level 3 · unit 2 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

and are delegates C# has already written.

Writing a new delegate type for every shape gets tiring, so C# ships two families. Func is for methods that give an answer back. The last type in its angle brackets is the answer, the ones before it are inputs: Func<int, int, int> takes two numbers and returns one.

Action is for methods that give nothing back, so every type is an input. Action<string> takes text and does something with it, like printing. Methods can take a Func or an Action as a parameter, which is how Where and Select accept your lambdas.

using System;

Func<int, int, int> add = (a, b) => a + b;
Func<string, int> letters = word => word.Length;
Func<int> answer = () => 42;
Action<string> cheer = text => Console.WriteLine(text.ToUpper() + "!");

Console.WriteLine(add(2, 3));
Console.WriteLine(letters("banana"));
Console.WriteLine(answer());
cheer("goal");

() => starts a lambda that takes no inputs at all.