.NET Zone is brought to you in partnership with:

I am former Microsoft MVP for Visual C# having 9 Year of experience in Microsoft.NET And other Microsoft Technologies. Please fill free to contact me at www.dotnetjalps.com Jalpesh is a DZone MVB and is not an employee of DZone and has posted 56 posts at DZone. You can read more from them at their website. View Full User Profile

Func Delegate in C#

08.25.2012
| 7816 views |
  • submit to reddit
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.

Func delegate in c#

That’s it. Hope you like it. Stay tuned for more updates.

Published at DZone with permission of Jalpesh Vadgama, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)