For example, currently Sam the TicketBooth Attendant is eating the last food object that was instantiated.
But what if he's not hungry for Meatloaf and instead wants to eat the Cheetah Chips? We can define a foreach loop that loops through his Food items and checks to see if the food item's Name is Cheetah Chips.
First we want to define the skeleton of the method. We want to return a type of Food and we want to be comparing to the name of the food Sam wants to we need to pass in an argument to compare to.
We will finish the method be defining a foreach loop.
In English this would be: We will loop through the list of Foods and if the food item in question's name is the same as the name we passed in then assign the foodFound variable to the food item in question and stop looping because we don't care about other stuff.
Now the first time we hit the foreach loop we can see that the foodFound is null and that the list has three items, the Cheetah Chips being the second.
When it loops through the first time it will check to see if the name of the current food item is the same as the name passed in.
It isn't so when we press F11 the debugger will go back to the foreach loop and go to the next item in the list.
In this second loop through we can see that the name of the current food item and the name passed in match...
...so the conditional will evaluate to true. When we press F11 the debugger will assign the foodFound variable to the current food item...
...and when we press F11 again, the debugger will 'break' out of the loop and hit the return statement. Again, once we find the match we don't care about the rest of the list.
Now we can pass in the foundFood variable as a parameter to the Eat method instead of forcing Sam to eat Meatloaf forever.
Foreach loops are not without their drawbacks, however. Note that in the example above, if we had another food item in the list later on that also had the name Cheetah Chips that one would have never been noticed.
Additionally, without a break statement the wrong thing might have been retrieved because the foundFood variable would always be assigned the last thing found. For example, let's say Sam isn't that hungry and is looking for a snack that only weighs a pound.
When the loop finds the Cheetah Chips it will assign the foundFood variable to the Cheetah Chips object...
...but without a break statement the loop will continue. When it does, it will find some sneaky Kale that Sam doesn't like and it will replace the Cheetah Chips as the object assigned to the foodFound variable.