c# · level 3 · unit 2 · lesson 2
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Do it twice. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
using System;
Console.WriteLine(ApplyTwice(n => n * 3, 2));
Console.WriteLine(ApplyTwice(n => n - 5, 20));
int ApplyTwice(Func<int, int> step, int start) => step(step(start));
your turn
Your turn. Price the parcels.
On line 3, write a lambda that works out a shipping price from the weight in kilos. Pick your own prices as decimal values, like 2.50m.
output
press run to see what happens
fix it
The area finder will not compile. Can you fix it?
output
press run to see what happens
- C# complains about the lambda on line 3. What does
n * ngive back, and where does it go? - An
Actionthrows away any answer, son * nhas nowhere to go. You need a delegate that returns. - Change
Action<int>toFunc<int, int>on line 3, then run.
nailed it
you can pass behaviour into any method. :D
Funcreturns a value: its last type is the answer.Actionreturns nothing: every type is an input.- Methods can take a
FuncorActionas a parameter.
new words in your collection
- Func
- Action
This lesson isn’t saved. A free account remembers every lesson you finish.