Friday, November 28, 2014

Func - generic delegate in C#

In this article, we will discuss about the concept of Func generic delegate. In C# 3.5, a generic delegate was provided with the keyword Func, which acts like a template for the user, to create and delegates. 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 :

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 :

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. By generic signature, here we mean that depending on the signature of the delegate we declared, its definition is displayed dynamically.

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.

So next time you need a delegate, go for this one. So this was all about the concept of Func delegate. Happy Coding...!!!

No comments:

Post a Comment