c# · level 3 · unit 2 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A is a type for methods.
So far your variables have held numbers, text and objects. Methods can be values too. A delegate is a type that describes a method's shape: what it takes and what it gives back. delegate decimal PriceRule(decimal price); describes any method that turns one price into another.
A variable of that type can hold a local function, or a lambda like the ones you wrote inside Where. Call it with brackets, as if it were the method itself. Swap in a different method and the same line of code does something new.
using System;
PriceRule rule = HalfPrice;
Console.WriteLine(rule(8.00m));
rule = price => price - 1.50m;
Console.WriteLine(rule(8.00m));
decimal HalfPrice(decimal price) => price / 2;
delegate decimal PriceRule(decimal price); The delegate type goes after the top-level code, with your other types.
guess first
A list of steps. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
using System;
using System.Collections.Generic;
var steps = new List<Step> { Tidy, Shout, text => text + "!" };
string message = " hello there ";
foreach (Step step in steps)
{
message = step(message);
}
Console.WriteLine(message);
string Tidy(string text) => text.Trim();
string Shout(string text) => text.ToUpper();
delegate string Step(string text);
your turn
Your turn. Decide who passes.
On line 3, give isPass a lambda that takes a score and says whether it passes. Choose your own pass mark, somewhere between 36 and 72.
output
press run to see what happens
fix it
The sale price will not compile. Can you fix it?
output
press run to see what happens
- C# says
TenOffdoes not match the delegate on line 3. Compare their shapes. PriceRuletakes and gives back adecimal, butTenOffusesdoublefor both.- Change both
doublewords on line 6 todecimal, then run.
nailed it
methods are values now. :D
- A delegate is a type that describes a method's shape.
- A delegate variable can hold a method or a lambda.
- Call it with brackets, like the method itself.
new words in your collection
- delegate
This lesson isn’t saved. A free account remembers every lesson you finish.