Hello Everyone, In this article we will talk about Func< in T, out TResult>
Delegate.
It is another readymade delegate that provides
by .Net framework. It can encapsulate a method that takes some parameters as
input and returns an output as TResult.
So in general Func is a delegate
Use case - Let's say An array is given and you have to print only odd numbers.
So in general Func is a delegate
1. Which takes from 0 to 16 parameters.
2. It is contra variant
and co variant both. Input parameters are contra variant and Output parameters
are co variant.
Where can we use Func delegate ?
You can use this delegate to encapsulate a method where you
need to pass some parameter( 0 to 16 ) and need to get some result. In this
case you do not need to explicitly create a delegate. Func is perfect
placeholder.
Let's see a complete example of Func delegate -Use case - Let's say An array is given and you have to print only odd numbers.
Solution - You can create a foreach loop and
check if the number is odd then print
that
At later stage of development you get some more rules added.
Let's say print those odd numbers which are greater than 5.
So in this case you have to modify your for loop which can
be at the UI level. In that case we will break some SOLID rules.
What is
the solution ?
We can create a Func that takes input of array and apply all
the rules and return list of data or one by one. This can be at model level and
UI won't be aware of the logic and functionality.
Hope you like reading the article. Please inbox me in case
of any confusion.
Happy Coding :)