Saturday, March 26, 2016

C# - Break And Continue

The "Break and continue"  are saved words in C# (you cannot use them as a name for variable/function...), these two terms are used to manipulate the Loop execution.

Continue

When using this "Continue" term, we actually tell the compiler that the current iteration is completed and therefore he need to finish with the current iteration and move to the next one.

Not like break, when using continue the loop will finish all iterations (if loop should run 20 times, the continue case will not cause any changes).
Example 1:

This example covers a simple loop without using any saved word, as a result, nothing will affect the loop execution
class Program
    {
        static void Main(string[] args)
        {
           int closeloop= 0;
            while (closeloop <= 5)
            {
                closeloop++;
            
                Console.WriteLine("Current iteration:{0} " , closeloop);   

                Console.WriteLine();

                Console.WriteLine("This code is reachable");
            }
        }
    }

 Result:
Example 2:
This example includes the ‘continue’ term, now you will  see that the code that appear afterwards will excluded on every  other iteration
class Program
    {
        static void Main(string[] args)
        {
           int closeloop= 0;
            while (closeloop <= 10)
            {
                closeloop++;      
                Console.WriteLine("Current iteration:{0} " , closeloop);
                continue;
                Console.WriteLine("This code is unreachable");
            }
        }
    }
Result:


Break
When using the ‘Break’ term, we are actually telling the compiler to END the entire loop execution (No matters how much more iterations are remained) and move to next code that appear after the loop.
Example 3:
This example demonstrates how the ‘Break’ ends the entire loop after the first iteration, and the execution will now move into the next code that appear after the loop.
class Program
    {
        static void Main(string[] args)
        {
           int closeloop= 0;
            while (closeloop <= 5)
            {
               closeloop++;
               Console.WriteLine("Current iteration:{0} " , closeloop);
               break;
               Console.WriteLine("This code is unreachable");
            }
            Console.WriteLine();
            Console.WriteLine("Code after breal");
        }
    }
Result:

No comments:

Post a Comment

My Presentations