September 11, 2020

Difference Between For and ForEach

ForEach loop - It is used to iterate through the items in a collection.  Foreach is very efficient. you do not need to know how many elements in collection.

For loop - We do intialisation, condition and increment at same place . you have to know how many times you have to loop through. we can use an exception as well.

Here is the example-

int[] numbers = new int[4];

            numbers[0] = 137;

            numbers[1] = 138;

            numbers[2] = 139;

            numbers[3] = 140;

            foreach (int k in numbers)

            {

                Console.Write(k);

            }

            for (int j = 0; j <= numbers.Length; j++)

            {

                Console.WriteLine(numbers[j]);

            }


In this, in case of for loop , if by mistaken we use <= symbol instead of < , we will get indexOutOfRange exception. So pretty much , best to use foreach loop...

No comments:

Post a Comment

Please let me know if you have any doubts.

Key concepts in Pipeline

 1. Agent- To build your code or deploy your software using azure pipelines, you need at least one agent. Two types of agent- Microsoft host...