Thursday, November 5, 2015

Predefined .net delegates Action, Func, Predicate

There are some predefined delegates provided by .net those makes code more simpler to write.

  1. Predicate: This delegate takes one input matches some condition and returns boolean value. This delegate is used to pass in functions of collection to match a condition, based on condition function returns collection items.
    ex.      Predicate<string> delPredicate = X => X.Length < 4;
    string
     myName = lstNames.Find(delPredicate);
  2. Action: This delegate takes one input and no output. This is used when out put not required and doing some operation with input inside as well.
    ex.  Action<string> delAction = G => Console.WriteLine(G);
  3. Func: This delegate has 17 overload methods, it returns 1 output and can take 1 to 16 inputs. This is used when we need output of some operation with providing 1 to 16 input parameters.
    Last parameter can be passed as output parameter if required.
    ex1     Func<intintint> delMulFunc = (x, y) => x * y;
    ex2     Func<intdouble> delTriangleArea = L => 3.14 * L * L;

Examples
class Program
{
    delegate int delAdd(int a, int b);

    static void Main(string[] args)
    {
    //Normal delegate
    delAdd delA = AddNum;
    int c = delA(50, 60);
    Console.WriteLine("Normal delegate: Value of c -" + c.ToString());

    //Lamda expression
    delAdd delLamda = (x,y) => x - y;
    int z = delLamda(70, 20);
    Console.WriteLine("Lamda expression: Value of z -" + z.ToString());

    //Ready made delegate Func
    Func<int, int, int> delMulFunc = (x, y) => x * y;
    int k = delMulFunc(20, 30);
    Console.WriteLine("Func: two input, Value of k -" + k.ToString());

    Func<int, double> delTriangleArea = L => 3.14 * L * L;
    double area = delTriangleArea(20);
    Console.WriteLine("Func: one input, Value of area :" + area.ToString());

    //Ready made delegate Action
    Action<string> delAction = G => Console.WriteLine(G);
    delAction("Action: Hello IT");

    //Ready made delegate Predicate
    Predicate<string> delPredicate = X => X.Length < 4;

    //use
    List<string> lstNames = new List<string> { "Ramu", "Raghu", "Raj", "Rajeev", "Ram" };
    string myName = lstNames.Find(delPredicate);
    Console.WriteLine("Predicate: Value of myName :" + myName);

    Console.ReadLine();
    }

    static int AddNum(int i, int j)
    {
        return i + j;
    }


}

No comments:

Post a Comment

CI/CD - Safe DB Changes/Migrations

Safe DB Migrations means updating your database schema without breaking the running application and without downtime . In real systems (A...