In this chapter you will learn:
- What is foreach loop in C#?
- How does it work?
- How to use foreach loop in C# programming?
foreach loop is a different kind of looping constructs in C# programming that doesn’t includes initialization, termination and increment/decrement characteristics. It uses collection to take value one by one and then processes them.
syntax:
1 2 3 4 |
foreach (string name in arr) { } |
Where, name is a string variable that takes value from collection as arr and then processes them in the body area.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace foreach_loop { class Program { static void Main(string[] args) { string[] arr = new string[5]; // declaring array //Storing value in array element arr[0] = "Steven"; arr[1] = "Clark"; arr[2] = "Mark"; arr[3] = "Thompson"; arr[4] = "John"; //retrieving value using foreach loop foreach (string name in arr) { Console.WriteLine("Hello " + name); } Console.ReadLine(); } } } |
Note: You will learn more about array in lateral chapter.
Output
Hello Steven
Hello Clark
Hello Mark
Hello Thompson
Hello John
__
Hello Clark
Hello Mark
Hello Thompson
Hello John
__
Summary
In this chapter you learned what foreach loop is and how to use it in C# programming. You also learned how to use foreach loop to access value from collection as array. In next chapter you will get some programming examples of loop constructs in C sharp.