Monday, March 13, 2017

Foreach Loop in C#

In this tutorial we are going to learn about foreach loop in c#. So let's start learning
  1. In for loop we use initialization, termination and increment or decrement to loop over the data but in foreach loop we are not required any initialization, condition or increment and decrement. It is a looping constructs which ignore/remove the errors which occur due to index handling.
  2. Mainly it performs its operation on collections like Array, Lists etc. and process inside values one by one.
  3. There are many ways to exit or stop the loop like if we want to break the loop we can use break keyword, if want to move on next iteration continue keyword, to exit the loop we can use return, throw or goto statement.
Syntax:-

foreach(string emp_id in employees)
{

}
Example:-

string[] employees = new string[3]; // declare the array 
    //Add data to array of employees
    array[0] = "Doe-1452";
    array[1] = "Joh-2365";
    array[2] = "Gen-2589"; 
    //show data using foreach
    foreach (string emp_id in employees)
    {
        Console.WriteLine(emp_id + " Entered to Office");
    }
    //Output
    Doe-1452 Entered to Office
    Joh-2365 Entered to Office
    Gen-2589 Entered to Office

No comments:

Post a Comment