Func Generic Delegate in C#

In C# 3.5, a generic delegate was provided with the keyword Func, that acts like a template for the user, to create delegates. The general signatures of this delegate is 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 the 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 taking two input parameters of type integer and the result is a Boolean value that specifies whether or not the first number is greater than the second. So our generic delegate signatures will be Func<Int32, Int32, Boolean>. Then we will be creating a function that will be encapsulated by this delegate.

See the code below:

CS Code

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:

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

call delegate

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.

CheckNumbers

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


Recommended Free Ebook
Similar Articles