What is Func<> and what is it used for?
I find Func very useful when I create a component that needs to be personalized "on the fly".
Take this very simple example: a PrintListToConsole component.
A very simple object that prints this list of objects to the console. You want to let the developer that uses it personalize the output.
For example, you want to let him define a particular type of number format and so on.
Without Func
First, you have to create an interface for a class that takes the input and produces the string to print to the console.
interface PrintListConsoleRender {
String Render(T input);
}
Then you have to create the class PrintListToConsole that takes the previously created interface and uses it over each element of the list.
class PrintListToConsole {
private PrintListConsoleRender _renderer;
public void SetRenderer(PrintListConsoleRender r) {
// this is the point where I can personalize the render mechanism
_renderer = r;
}
public void PrintToConsole(List list) {
foreach (var item in list) {
Console.Write(_renderer.Render(item));
}
}
}
The developer that needs to use your component has to:
implement the interface
pass the real class to the PrintListToConsole
class MyRenderer : PrintListConsoleRender {
public String Render(int input) {
return "Number: " + input;
}
}
class Program {
static void Main(string[] args) {
var list = new List { 1, 2, 3 };
var printer = new PrintListToConsole();
printer.SetRenderer(new MyRenderer());
printer.PrintToConsole(list);
string result = Console.ReadLine();
}
}
Using Func it's much simpler
Inside the component you define a parameter of type Func that represents an interface of a function that takes an input parameter of type T and returns a string (the output for the console)
class PrintListToConsole {
private Func _renderFunc;
public void SetRenderFunc(Func r) {
// this is the point where I can set the render mechanism
_renderFunc = r;
}
public void Print(List list) {
foreach (var item in list) {
Console.Write(_renderFunc(item));
}
}
}
When the developer uses your component he simply passes to the component the implementation of the Func type, that is a function that creates the output for the console.
class Program {
static void Main(string[] args) {
var list = new List { 1, 2, 3 }; // should be a list as the method signature expects
var printer = new PrintListToConsole();
printer.SetRenderFunc((o) => "Number:" + o);
printer.Print(list);
string result = Console.ReadLine();
}
}
Func lets you define a generic method interface on the fly.
You define what type the input is and what type the output is.
Simple and concise.