Func – the generic delegate in C#


In one of my posts, we discussed the concept of delegates, with a simple example. You can check out that one here. For this, we were required to create a delegate and then uses this delegate to call a method that matched the signature of the defined delegate.

In C# 3.5, a generic delegate was provided with the keyword Func. The general signatures of this delegate are  Func<T, TResult>.

Here, T is the input parameter for the method and TResult is the return parameter of the method that will be called using this delegate. This is just a single declaration. You can have the signatures like Func<Int32, Int32, Boolean> or Func<String, Int32, Int32, Boolean>. Here, the last parameter is always the result type and rest of them are the input parameter types of the methods, that can be encapsulated by these delegates.

So let’s discuss this with a simple example. We will be creating a delegate which will take two input parameters of type integer, and result a boolean value, which specifies whether the first number is greater then second or not. So our generic delegate signatures will be Func<Int32, Int32, Boolean>. Then we will be creating a function which will be encapsulated by this delegate.

See the code below :

1

Next, to use this delegate, we will be assigning the method with the same signatures, to this delegate and call the delegate object and pass the required parameters to it. Check out the code below :

2

So this will return the true or false, based on your input parameters. Similarly, you can declare the delegate with more parameters, of the required type. If you try to go to the definition of this declared delegate, it will display the generic signatures of it, like below. Generic signature, here we mean that depending on the signature of this delegate, its definition is displayed dynamically.

3

One more interesting point is the use of the anonymous methods or the lambda expression with this delegate. You could have avoided writing the method CheckNumbers, by using the following anonymous or lambda expression declarations.

4

So next time you need a delegate, go for this one. So this was all about the Func delegate.

Happy Coding…!!!

Advertisements

About Jasminder

.Net developer and blogger by profession, keen to learn new technologies, love nature, music and cricket.
This entry was posted in C#. Bookmark the permalink.

I have a suggestion..

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s