Func Delegate in C#
- by Jalpesh P. Vadgama
We already know about delegates in C# and I have previously posted about basics of delegates in C#. Following are posts about basic of delegates I have written. Delegates in C# Multicast Delegates in C# In this post we are going to learn about Func Delegates in C#. As per MSDN following is a definition. “Encapsulates a method that has one parameter and returns a value of the type specified by the TResult parameter.” Func can handle multiple arguments. The Func delegates is parameterized type. It takes any valid C# type as parameter and you have can multiple parameters and also you have specify the return type as last parameters. Followings are some examples of parameters. Func<int T,out TResult> Func<int T,int T, out Tresult> Now let’s take a string concatenation example for that. I am going to create two func delegate which will going to concate two strings and three string. Following is a code for that. using System;
using System.Collections.Generic;
namespace FuncExample
{
class Program
{
static void Main(string[] args)
{
Func<string, string, string> concatTwo = (x, y) => string.Format("{0} {1}",x,y);
Func<string, string, string, string> concatThree = (x, y, z) => string.Format("{0} {1} {2}", x, y,z);
Console.WriteLine(concatTwo("Hello", "Jalpesh"));
Console.WriteLine(concatThree("Hello","Jalpesh","Vadgama"));
Console.ReadLine();
}
}
}
As you can see in above example, I have create two delegates ‘concatTwo’ and ‘concatThree. The first concat two strings and another concat three strings. If you see the func statements the last parameter is for the out as here its output string so I have written string as last parameter in both statements. Now it’s time to run the example and as expected following is output.
That’s it. Hope you like it. Stay tuned for more updates.