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
List
foreach (int salary in filterSalary)
{
Console.WriteLine("Main Method: " + salary);
}
}
// Get all salary which is higher than 5000.
private static List
{
List
{
// 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: 8500CheckSalary 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
foreach (int salary in CheckSalary(empSalary))
{
Console.WriteLine("Main Method: " + salary);
}
}
// Get salary which is higher than 5000.
private static IEnumerable
{
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: 8500Main 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