In this C# Loop tutorial you will learn different type of loops in C# with examples, like any other programming language, .net c# also provides looping structure; the syntax may differ from other programming language, so these examples will help you to understand better.
From the word "loop" you can understand that a control structure that will help to execute any code multiple times, in some cases you may know how many times the same code to be executed, and sometimes you may know the number at runtimes.
int bCount =0
bCount <= 10
bCount++
, which mean bCount= bCount+1
{ loop body }
, In body, we define all our business logic to be executed.
In real time C# .Net application development you may come across many such situation where you need to write a loop
For loop is simple, when you know how many times some code block to be executed there you write for loop, for example if you know your code blook to be excuted for 10 times
for (int i = 1; i <= 10; i++) { /* here you write code to be executed */ }
Foreach loop is often used to run loop through a object list collection, in below example we don’t know how many blog we have in the list.
foreach (blogObj b in blogList) { /* for example here you write code to display any property of each blog */ }
while loop includes a Boolean expression as a condition, which returns true or false. It executes the code block, as long as the specified conditional expression returns true.
While(boolean expression) { //execute code as long as condition returns true } int i = 0; while (i < 5) { Console.WriteLine("Value of i: {0}", i); i++; }
do while loop is the same as a 'while' loop, but there while clause is at the end, when condition satisfied, then it exit the loop
do { //execute code block } while(boolean expression); int i = 0; do { Console.WriteLine("print the value of i: {0}", i); i++; } while (i < 5);
Note: if you want to come out of the loop for any addition exception condition use keyword break
Sometimes you may need to write a loop inside a loop, which is known as Nested loop in c#.
Think of situation where you need to loop through list collection and each object contain a list of images, so you have to loop through files.
foreach (blogObj b in blogList) { foreach(image in blogObj.Images) { // capture each image info. } }
You can loop through array or loop through any object, that can be simple string array or files in folder
string[] animals = { "tiger", "bird", "cat", "dog" }; foreach (string s in animals) { Console.WriteLine(s); }//loop through files in folder
// or file collection File[] files = MyFolder.GetFiles(); foreach (File f in files) { // f contain each file object Console.WriteLine(f.Name); }