In c#, Func is a built-in generic delegate. It is useful to hold the reference of one or more methods with the same method signature without declaring any custom delegate object.
In previous chapters, we learned about delegates and will be used as shown following to hold the reference of methods with the same signature.
If you observe the above example, we created a delegate object called “SampleDelegate” to hold the reference of Add & Subtract methods.
When we execute the above example, we will get the result as shown below.
To avoid the declaration of custom delegate object (SampleDelegate), as we defined in the above example, the generic built-in delegates such as Func, Action, Predicate have been introduced in C# 3.0.
C# 3.0 onwards, the Func delegate will be available automatically with the System namespace, and it will accept zero or more (16) input parameters and one output parameter.
Following is the syntax of declaring a Func delegate with one input parameter and one output parameter in c#.
Here, the last parameter in the angle bracket < >
will be considered as an output parameter (return type), and the remaining all are considered as input parameters.
Parameter | Description |
---|---|
TResult | It represents the type of return value of the method that the delegate encapsulates. |
T | It represents the type of parameter of the method that the delegate encapsulates. |
If we want to create a Func delegate with two input parameters and return type (output parameter), that would be as shown below.
Like this, a Func delegate can include 0 to 16 input parameters of different types and one output parameter for the result.
Following is the example of defining the Func delegate to hold the reference of one or more methods which is having the same method signature.
If you observe the above example, we created a Func delegate object (dlgt) with two input parameters (int) and one output parameter (int) to return an int value.
Here, the declaration of Func<int, int, int> dlgt is same as the SampleDelegate object in the previous example.
When we execute the above example, we will get the result as shown below.
Every time while creating the Func delegate, we must need to remember that we can include 0 to 16 input parameters of different types, and that is optional, but we must need to include one output parameter for the return type.
Following is the example of creating a Func delegate with zero (0) input parameters and one output parameter.
In c#, we can assign the anonymous method directly to the Func delegate by using the delegate keyword like as shown below.
If you observe the above code, we assigned an anonymous method directly to the Func delegate object (dlgt) using the delegate keyword.
In c#, we can also use a Func delegate with lambda expressions. The lambda expressions are the shorthand way of declaring the anonymous method.
Following are the important points which we need to remember about Func delegate in c#.