Saturday, July 18, 2015

Break vs continue

It is very important to know the differences between this two, especially in the loop.
If you use break, you will go out from the loop;
If you use continue, you will continue to the next looped item.


Both will result the next / remaining code not excecuted.
string[] abc = new string[] { "A""B""C" };
int count1 = 0, count2 = 0, count3 = 0;
 
foreach (string a in abc)
{   
    count1++; 
}
//count1 = 3
 
foreach (string a in abc)
{
    if (a == "B")
        break;
    count2++;
}
//count2 = 1
 
foreach (string a in abc)
{
    if (a == "B")
        continue;
    count3++;
}

//count3 = 2

No comments:

Post a Comment