Click here to Skip to main content
15,880,905 members
Articles / Programming Languages / C#

Looking in Func Delegates

Rate me:
Please Sign up or sign in to vote.
4.93/5 (13 votes)
19 Dec 2010CPOL1 min read 40.4K   11   6
This is an extension of my earlier blog post.

This is an extension of my earlier blog post. I myself, find delegates as one of the most powerful types to use in C#. It helps in writing very flexible and scalable programs.

I already discussed in my last blog that in the traditional way, we need to write more code. There I also discussed, one predefined delegate Action delegate that is provided by the framework. There are four flavors of Action delegate provided.

One more type of predefined delegate that is provided by .NET is the counterpart Action delegate. As we saw, it always returns void. But Func returns a value instead of void as Action does.

There are also 5 flavours of the Func delegate that are provided. These are:

C#
Public delegate TResult Func<TResult>()
  • C#
    Public delegate TResult Func<TResult>()  // Take no parameter and return a value
  • C#
    Public delegate TResult Func<T, TResult>(T t)  // Take one input parameter 
    					 // and return a value
  • C#
    Public delegate TResult Func<T1, T2, TResult>(T1 t1, T2 t2)  // Take 2 input 
    					// parameters and return a value
  • C#
    Public delegate TResult Func<T1, T2, T3, TResult>(T1 t1, T2 t2, T3 t3)  // Take 3 
    					// input parameter and return a value
  • C#
    Public delegate TResult Func<T1, T2, T3, T4, TResult>
        (T1 t1, T2 t2, T3 t3,T4 t4)  // Take 4 input parameter and return a value

If we see the declaration, TResult is put last, this is just a convention. One can put it wherever s/he wants.

First let's see first one, with no parameter and returning a value:

C#
public class Program
{
static void Main(string[] args)
{
//Creating the Func variable and assigning it a function
Func<string> myFunc = SayHello;

//Calling function using Func Delegate
string returnedString = myFunc();

Console.WriteLine(returnedString);

Console.ReadKey();
}

private static string SayHello()
{
return "Hello Dude!!";
}
}

Now let's move to code to another overload of Func Delegate. It takes two input parameters and returns a value.

C#
public class Program
{
static void Main(string[] args)
{
//Creating the Func variable (which takes two input parameters and returns a value) 
//and assigning it a function
Func<double, double, double> myFunc1 = Add;

//Calling function using Func Delegate
double sum = myFunc1(3.5, 4.5);

Console.WriteLine(sum);

Console.ReadKey();
}

private static double Add(double first, double second)
{
return first + second;
}
}

It is also the same as Action delegate, i.e., it can also be used with Anonymous functions and Lambda functions. Let's have a quick look at both:

Anonymous Function

C#
public class Program
{
static void Main(string[] args)
{
//Creating the Func variable (which takes three input parameters and returns a value) 
//and assigning it an Anonyomus function
Func<double, double, double, double> myFunc1 = delegate(double d1, double d2, double d3)
{
return d1 + d2 + d3;
};

//Calling function using Func Delegate
double sum = myFunc1(3.5, 4.5, 5.5);

Console.WriteLine(sum);

Console.ReadKey();
}
}

Lambda Function

C#
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Program
{
static void Main(string[] args)
{

Func<Employee,string> checkEmployee = s=>{
if (s.Id > 11)
return s.Name;
else
return "Employee is not with the given Criteria.";
};

Console.WriteLine(checkEmployee(new Employee() {Id=12, Name="Brij"}));
Console.WriteLine(checkEmployee(new Employee() {Id=10, Name="Abhijit"}));

Console.ReadKey();
}
}

Hope you all enjoyed the delegates.

We use delegates a lot. But most of us use the traditional way in programs. When I learnt first these Action and Func delegates a few weeks ago, I found them very useful. It helps us in writing better and well organised code, which is also less error prone. I talked to a lot of developers, they didn’t have any idea about these predefined delegates. So I thought of sharing with all of you.

Please share your valuable feedback.

Cheers,

Brij


License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India
Brij is a 3-times Microsoft MVP in ASP.NET/IIS Category and a passionate .NET developer. More than 6 years of experience in IT field, currently serving a MNC as a Tech Lead/Architect.

He is a very passionate .NET developer and have expertise over Web technologies like ASP.NET 2.0/3.5/4.0, jQuery, JSON, Javascript, IIS and related technologies. He is also a Exchange Server (EWS) Specialist. He has great experience in design patterns and N-Tier Architecture.

He is also certified as Microsoft Certified Technologies Specialist-ASP.NET and Microsoft Certified Technologies Specialist-WCF in .NET 4.0. He has also received several awards at various forums and his various articles got listed as "Article of the day" at ASP.NET Microsoft Official Website www.asp.net.

He has done MCA from NIT Durgapur and completed his graduation from Lucknow University.

Learning new technologies and sharing knowledge excites him most. Blogging, solving problems at various forums, helping people, keeps him busy entire day.


Visit his Blog: Code Wala

Area of Expertise :
C#, ASP.NET 2.0,3.5,4.0, AJAX, JQuery, JSON, XML, XSLT, ADO.Net, WCF, Active Directory, Exchange Server 2007 (EWS), Java script, Web Services ,Win services, DotnetNuke, WSS 3.0,Sharepoint Designer, SQL Server 2000/2005/2008

Comments and Discussions

 
QuestionGreat Article Pin
Pradip Kumar Sen31-Dec-14 0:14
professionalPradip Kumar Sen31-Dec-14 0:14 
QuestionLooking in Func Delegates Pin
rich123xyz10-Jan-14 13:22
rich123xyz10-Jan-14 13:22 
QuestionIt is good article, But we can call function without delegate, so what is the use? Pin
Sai Sherlekar22-Apr-13 22:05
Sai Sherlekar22-Apr-13 22:05 
I like ur article, it is well written and understandable.

But i didnt get one point what is the use of delegate,

we can do above things without delegate also.

please reply

thnx in advance.
AnswerRe: It is good article, But we can call function without delegate, so what is the use? Pin
mohan5k3-Jun-15 9:17
professionalmohan5k3-Jun-15 9:17 
GeneralMy vote of 5 Pin
Dilip Baboo10-Mar-11 11:00
Dilip Baboo10-Mar-11 11:00 
GeneralRe: My vote of 5 Pin
Brij11-Mar-11 17:57
mentorBrij11-Mar-11 17:57 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.