Func is a generic delegate introduced in .Net framework version 3.5. Generally, whenever we want to create delegate, we follow below procedure:
- Create delegate that matches the format of method.
- Create an instance of delegate and point it to that method.
- Invoke that method via delegate.
But via Func delegate, we can simplify above procedure.
- Func delegate is generic so you can provide any types to this delegate as input parameters.
- Func<> can point to a method which is supposed to return a value.
- Always remember that, Func’s last parameter is return the value of method. Like if we have declared Func<int,string> it means this Func will take int as input and return string value.
- Func<> can take 16 parameters as input and return a single value. Func<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16,TResult> Delegate. Encapsulates a method that has 16 parameters and returns a value of the type specified by the TResult parameter.
- Its not always necessary that you have to provide method as body. You can also provide anonymous body to Func. So whenever Func will be called, anonymous code block will be executed.
Lets see an example of this delegate. You have a requirement where you need to find all numbers which are greater that 5 from an integer array. So you will create a method which will return only those numbers which are greater than 5. See below example.
Now, We’ve new requirement which says that we need to find all numbers which are divisible by 2. So you will create new method which satisfy this requirement. But using Func<> you can solve this kind requirements with single method only. See below example.
Happy coding!