Tuesday 7 January 2020

What is Func, how and when it can be used, examples

Func is a predefined delegate. .Net have 17 Func delegates with different parameters from 1 to 17. Every Func delete last parameter is return type says TResult. It encapsulte a method which have zero (0) to 16 parameters, except the last one, rest of the parameters are function input parameter.
Let's see how it is defined internally
  1. public delegate TResult Func<out TResult>();
  2. public delegate TResult Func<in T, out TResult>(T arg);
  3. public delegate TResult Func<in T1, in T2, out TResult>(T1 arg1, T2 arg2);
  4. public delegate TResult Func<in T1, in T2, in T3, out TResult>(T1 arg1, T2 arg2, T3 arg3);
  5. ...............
  6. ...............
  7. public delegate TResult Func<in T1, in T2, ...., in T16, out TResult>(T1 arg1, T2 arg2, ..., T16 arg16);
Now we have a clear picture how it is defined by Microsoft, check it yourself

Why we need to know this?

There are many functions which accept Func as parameter, if we don't know about Func delegate we cannot use them property. There are many functions which we are using every day but we don't know that they accept parameter as Func, let's see some of the examples to understand it better
Let's see it with an array of integers and apply where, order by on it
  1.  int[] arr = {1, 3, 2, 4, 6, 5, 7, 9, 8, 10 };    
  2.  var evenItems = arr.Where(x => x % 2 == 0);    
  3.  var sortedArray= arr.OrderBy(x => x);
Where and OrderBy are functions, do you know what are the parameter type they accept, it is Func
.Where(Func<int, bool> predicate)    .OrderBy(Func<int, int> keySelector) 
To understand it, we need to use our 10th class Math function writing style, let's see
  1.  f(x) => x + 10  // Add 10 to x
  2.  g(x) => x * x   // Square of x
  3.  h(x) => x % 2 == 0
  4.  j(x,y) => x == y // Equality test
Now let's take our Where and h`(x) examples together
 .Where(Func<int, bool> predicate)
 h(x) => x % 2 == 0
h(x) accept one parameter as integers and return true if devisible by 2 otherwise false.
In the same way our Where function accept a Func with two parameter an integer(input) and bool(output).

Use Func for our math examples

We are going to write our above Math function into Func format
  1. Func<int, int> f = x => x + 10;             // f(x)
  2. Func<int, int> g = x => x * 10;             // g(x)
  3. Func<int, bool> h = x => x % 2 == 0;        // h(x)
  4. Func<int, int, bool> j = (x, y) => x == y;  // f(x)

Func usage and examples

Let's say we have to write a function which can accept any two type of input parameters and return any type by adding them, where we will end? We will be writing separate method for short, int, long, single, double, string ... and many more. Can we use Func delegate here, of course, let's see it one by one
To add two integers and return integer
Func<int, int, int> myAddition = (x, y) => x + y; Console.WriteLine(myAddition(10, 20)); 
To add two string and return an string
Func<String, String, String> myStringAddition = (x, y) => x + y; Console.WriteLine(myStringAddition("Hellow ", "World!")); 
To add two single and return a double
Func<Single, Single, Double> mySingleAddition = (x, y) => (Double)(x + y); Console.WriteLine(mySingleAddition(10.10f, 15.25f)); 
If I ask to write a function to check the pythagorous theoram where will you end, let's see without Func first
  1. public static bool IsPythagoreanValuea(int length, int height, int hypotenuse)
  2. {
  3.     var a = length * length;
  4.     var b = height * height;
  5.     var ab = a + b;
  6.     var c = hypotenuse * hypotenuse;
  7.     if (ab == c)
  8.         return true;
  9.     else
  10.         return false;
  11. }  
The same function we can write with Func delegage like this:
Func<int, int, int, bool> IsPythagoreanValue = (x, y, z) => x * x + y * y == z * z; Console.WriteLine(IsPythagoreanValue(4, 3, 5)); 
Is not it easy and simple to use.

Func with void return method

As we discuss Func always use last parameter as return type, if a function don't accept any parameter and return something then we use Func<RetrunType>. So it is create Func cannot be used for a function with return type void rather we can use Action, see the example
Say we have some function like this:
  1. public static void SomeFunction(int i, string str)
  2. {
  3.   // Some code here
  4. }
Our SomeFunction returns void so we can use Action:
var action = new Action<int, string>(SomeFunction); Or Action<int, string> action = SomeFunction; 

No comments:

Post a Comment

Baisic Useful Git Commands

  Pushing a fresh repository Create a fresh repository(Any cloud repository). Open terminal (for mac ) and command (windows) and type the be...