Friday, January 4, 2013

What is Deffered Execution in c#?

Deffered Execution

Deferred execution is the important concept of C#. To understand the deferred execution, first have a look on the below code:


static void Main()
{
       // List of 10 employee salary.
       List empSalary = new List { 3500, 2400, 8500, 6800, 7500, 9500, 2800, 6500, 4500, 7000 };

       List filterSalary = CheckSalary(empSalary);

       foreach (int salary in filterSalary)
      {
            Console.WriteLine("Main Method: " + salary);
       }
}

// Get all salary which is higher than 5000.
private static List CheckSalary(List employeeSalary)
{
    List result = new List();
    foreach (int salary in employeeSalary)
   {
       // Check the salary is greater than 5000 or not.
       if (salary > 5000)
       {
       result.Add(salary);
       Console.WriteLine("CheckSalary Method: " + salary);
       }

   }
   return result;
}

Result

CheckSalary Method: 8500
CheckSalary Method: 6800
CheckSalary Method: 7500
CheckSalary Method: 9500
CheckSalary Method: 6500
CheckSalary Method: 7000
Main Method: 8500
Main Method: 6800
Main Method: 7500
Main Method: 9500
Main Method: 6500
Main Method: 7000

In the above code CheckSalary method takes a list of employee salary as a parameter and returns the filter salary list i.e. Main method will get the filter salary list in one shot but in case of deferred execution, Main method will get filter salary one by one. Have a look on below code:

static void Main()
{
// List of 10 employee salary.
List empSalary = new List { 3500, 2400, 8500, 6800, 7500, 9500, 2800, 6500, 4500, 7000 };

foreach (int salary in CheckSalary(empSalary))
{
Console.WriteLine("Main Method: " + salary);
}
}

// Get salary which is higher than 5000.
private static IEnumerable CheckSalary(List employeeSalary)
{
foreach (int salary in employeeSalary)
{
// Check the salary is greater than 5000 or not.
if (salary > 5000)
{
Console.WriteLine("CheckSalary Method: " + salary);
yield return salary;
}

}
}

Result

CheckSalary Method: 8500
Main Method: 8500
CheckSalary Method: 6800
Main Method: 6800
CheckSalary Method: 7500
Main Method: 7500
CheckSalary Method: 9500
Main Method: 9500
CheckSalary Method: 6500
Main Method: 6500
CheckSalary Method: 7000
Main Method: 7000

In above result, you can see that first CheckSalary method compares the salary and if salary > 5000 then it deferred the execution and return the result to Main method by yield keyword. Once the Main method execution gets complete then it comes back to the CheckSalary method to compare the rest salary.

No comments:

Post a Comment