Reflection on Flow Control in C#

In C#, Flow-Control is used regularly.  It determines our program’s logic.  

I have encountered some issues while using them, even though the syntax is quite simple.  These issues are not complex, but it can be serious if I ignore them.

While in C#

//While Statement
while(var i = 0; i += 1; i <= 10) {
    
}

The While statement is straight forward, it keeps running till the variable i reaches 10. In the beginning, I thought the loop will run 10 times; however, it will run 11 times, as the value of i is 0 in the beginning.


If-Statement and Do-While Statement

Do-While statement is similar with While statement, which loops through repeating action till it reaches certain condition; whereas If-statement execute the code depends on condition.

//If Statement
if (true) {
    //Code in If-Statement
}

In If-Statement, the code in If-Statement will be executed if the condition is true; otherwise, the code will never be executed.

//Do-While Statement
do {
    //Code in Do-While Statement
} while ();

However, the code in Do-While statement will be executed at least once regardless of the condition.


Break and Continue

break;

break – it breaks out of the loop entire when compiler run into it.

continue;

continue – it skips certain lines of code and keep looping.


Leave a Reply

Your email address will not be published. Required fields are marked *