
Func Template Delegates
C# has an interesting delegate option, Func. Func is nothing but a syntactic sugar over classic delegate template, but it does make it simple to process and to read. If we have the following code using delegate
static int Factorial(int source)
{
int first=1;
for (int i=1;i<=source;i++)
{
first*=i;
}
return first;
}
delegate T SingleMath<T,T1>(T1 arg);
SingleMath<int,int> singleMath=Factorial;
Code language: C# (cs)
We can also write the same exact thing using Func:
static int Factorial(int source)
{
int first=1;
for (int i=1;i<=source;i++)
{
first*=i;
}
return first;
}
Func<int,int> mathFunc=Factorial;
Code language: C# (cs)
This is both clearer and shorter. we can pass a value of this delegate the same way:
static int DoSomething(int source,Func<int,int>)
{
}
Code language: C# (cs)
This can be used in functional programming schema. Templates can also be used in a template based as well:
static int DoSomething(int source,Func<T,T1>)
{
}
Code language: C# (cs)
In the example above, T1 and T can be different or the same parameter types.