Saturday, August 25, 2012

Func Delegate in C#

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 as well you have to 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"));

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.


Your feedback is very important to me. Please provide your feedback via putting comments.

Support this blog-Buy me a coffee

Buy me a coffeeBuy me a coffee
Search This Blog
Subscribe to my blog


My Mvp Profile
Follow us on facebook
Blog Archive
Total Pageviews