Delegates and Lambdas
Func and Action
Func returns a value, while Action performs work without returning one.
Func and Action
`Func` delegates return values, and `Action` delegates return `void`.
Func and Action
FuncAction.cs
Replay: real traced execution (multi-file project)
using System;
class Program
{
static void Main()
{
string word = "ready";
Func<string, string> bracket = text => "[" + text + "]";
string output = "";
Action<string> save = text => output = text;
save(bracket(word));
Console.WriteLine($"word={word}");
Console.WriteLine($"output={output}");
}
}
using System;
class Program
{
static void Main()
{
string word = "done";
Func<string, string> bracket = text => "[" + text + "]";
string output = "";
Action<string> save = text => output = text;
save(bracket(word));
Console.WriteLine($"word={word}");
Console.WriteLine($"output={output}");
}
}
using System;
class Program
{
static void Main()
{
string word = "start";
Func<string, string> bracket = text => "[" + text + "]";
string output = "";
Action<string> save = text => output = text;
save(bracket(word));
Console.WriteLine($"word={word}");
Console.WriteLine($"output={output}");
}
}
word ← ready, bracket ← System.Func`2[System.String,System.String]
4{5 static void Main()6 {7 string word→ ready = "ready"; //@word="done", "start"8 Func<string, string> bracket→ System.Func`2[System.String,System.String] = text => "[" + text + "]";9 string output→ (empty) = "";10 Action<string> save→ System.Action`1[System.String] = text => output = text;1112 save(bracket(wordready));1314 Console.WriteLine($"word={wordready}");15 Console.WriteLine($"output={output[ready]}");16 }outputword=ready output=[ready]
word ← done, bracket ← System.Func`2[System.String,System.String]
4{5 static void Main()6 {7 string word→ done = "done";8 Func<string, string> bracket→ System.Func`2[System.String,System.String] = text => "[" + text + "]";9 string output→ (empty) = "";10 Action<string> save→ System.Action`1[System.String] = text => output = text;1112 save(bracket(worddone));1314 Console.WriteLine($"word={worddone}");15 Console.WriteLine($"output={output[done]}");16 }outputword=done output=[done]
word ← start, bracket ← System.Func`2[System.String,System.String]
4{5 static void Main()6 {7 string word→ start = "start";8 Func<string, string> bracket→ System.Func`2[System.String,System.String] = text => "[" + text + "]";9 string output→ (empty) = "";10 Action<string> save→ System.Action`1[System.String] = text => output = text;1112 save(bracket(wordstart));1314 Console.WriteLine($"word={wordstart}");15 Console.WriteLine($"output={output[start]}");16 }outputword=start output=[start]