Codiqo

Learn C# · lesson 58 of 61 · about 9 minutes

Func, Action and Lambdas

Store methods in variables and pass them to other methods.

What you'll learn

  • Store a lambda in a Func or Action
  • Pass a method as an argument
  • Return a function from a method

Inside the lair

The key turns, the gate opens, and deep inside the lair the dragon wakes: The dragon roars: WHO DARES WAKE ME!. Its scales soak up 3 from every hit, so the combo needs an edge. The hero has a whetstone that adds a fifth of the power inside the wards to each hit. This last unit of the course finishes the battle, and its first lesson keeps whole pieces of behaviour in variables: the roar is an Action<string>, the whetstone is a function made by a method, and one Strike method adds up the combo with whichever damage function it's handed, First strike: 8 damage through the scales (2 without the whetstone).

Methods as values

You've written lambdas like x => x * 2 for LINQ. You can also keep one in a variable, using a delegate type:

  • Func<int, int> takes an int and returns an int (the last type is always the return type)
  • Func<int, int, int> takes two ints and returns one
  • Action<string> takes a string and returns nothing
  • Predicate<int> takes an int and returns a bool

Storing lambdas

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(7));
Console.WriteLine(add(2, 3));
shout("hello");

Output

49
5
HELLO!

Passing and returning functions

A method can take a Func parameter and call it, so the caller decides what happens. A method can also return a function: MakeMultiplier(3) can return x => x * 3, which remembers the 3.

Higher-order methods

int[] nums = [1, 2, 3, 4];
Console.WriteLine(string.Join(" ", Apply(nums, x => x + 10)));

Func<int, int> triple = MakeMultiplier(3);
Console.WriteLine(triple(5));

static int[] Apply(int[] items, Func<int, int> f)
{
    int[] result = new int[items.Length];
    for (int i = 0; i < items.Length; i++) result[i] = f(items[i]);
    return result;
}

static Func<int, int> MakeMultiplier(int factor) => x => x * factor;

Output

11 12 13 14
15

Through the scales

Sharpen(lairPower / 5) gives back a function, d => d + bonus, that remembers its bonus, so whetstone(4) is 7 when the power inside the wards is 15. sharp is a Func<Attack, int> that runs an attack's DragonDamage through the whetstone and takes off the 3 the scales soak, and blunt does the same without the whetstone. Math.Max(0, ...) stops a fire, which does nothing to this dragon, from counting as less than nothing. Strike doesn't know which of them it's been given: it calls hitFor(a) for every attack in the combo and adds up the answers. The roar is an Action<string>, because it only prints and gives nothing back.

Tip

A method name can be passed wherever a matching delegate is expected: Apply(nums, Math.Abs) works because Math.Abs takes an int and returns an int.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.