Delegates and Lambdas
Method Groups
A method name can be assigned to a compatible delegate variable.
method group
A method group is a method name used where a delegate is expected.
Method Groups
MethodGroups.cs
Replay: real traced execution (multi-file project)
using System;
class Program
{
static int AddTax(int cents)
{
return cents + 5;
}
static void Main()
{
int price = 40;
Func<int, int> calculator = AddTax;
int total = calculator(price);
Console.WriteLine($"price={price}");
Console.WriteLine($"total={total}");
}
}
using System;
class Program
{
static int AddTax(int cents)
{
return cents + 5;
}
static void Main()
{
int price = 20;
Func<int, int> calculator = AddTax;
int total = calculator(price);
Console.WriteLine($"price={price}");
Console.WriteLine($"total={total}");
}
}
using System;
class Program
{
static int AddTax(int cents)
{
return cents + 5;
}
static void Main()
{
int price = 75;
Func<int, int> calculator = AddTax;
int total = calculator(price);
Console.WriteLine($"price={price}");
Console.WriteLine($"total={total}");
}
}
price ← 40, calculator ← System.Func`2[System.Int32,System.Int32]
10static void Main()11{12 int price→ 40 = 40; //@price=20, 7513 Func<int, int> calculator→ System.Func`2[System.Int32,System.Int32] = AddTax;14 int total = calculator(price40);static int AddTax(int cents)
4{5 static int AddTax(int cents40)6 {7 return cents40 + 5;8 }total ← 45
13 Func<int, int> calculator = AddTax;14 int total→ 45 = calculator(price40);1516 Console.WriteLine($"price={price40}");17 Console.WriteLine($"total={total45}");18}outputprice=40 total=45
price ← 20, calculator ← System.Func`2[System.Int32,System.Int32]
10static void Main()11{12 int price→ 20 = 20;13 Func<int, int> calculator→ System.Func`2[System.Int32,System.Int32] = AddTax;14 int total = calculator(price20);static int AddTax(int cents)
4{5 static int AddTax(int cents20)6 {7 return cents20 + 5;8 }total ← 25
13 Func<int, int> calculator = AddTax;14 int total→ 25 = calculator(price20);1516 Console.WriteLine($"price={price20}");17 Console.WriteLine($"total={total25}");18}outputprice=20 total=25
price ← 75, calculator ← System.Func`2[System.Int32,System.Int32]
10static void Main()11{12 int price→ 75 = 75;13 Func<int, int> calculator→ System.Func`2[System.Int32,System.Int32] = AddTax;14 int total = calculator(price75);static int AddTax(int cents)
4{5 static int AddTax(int cents75)6 {7 return cents75 + 5;8 }total ← 80
13 Func<int, int> calculator = AddTax;14 int total→ 80 = calculator(price75);1516 Console.WriteLine($"price={price75}");17 Console.WriteLine($"total={total80}");18}outputprice=75 total=80