+ 2
Anyone who understands the function of break statement in C#
Ever since I started coding, the break statement had been a huge fail in my codes. Pls anyone who fully understands the function of break statement in C# should leave behind a comment P.S.: I really mean it guys, thanks 👍
4 Antworten
+ 3
The `break` keyword is used to immediately terminate from the scope of a loop.
+ 1
Here's a good example. This code is purely pseudo and will not compile for (hopefully) obvious reasons
public void DoBattle(Player player, Enemy enemy)
{
while(enemey.health > 0)
{
player.attack();
if(enemey.health <= 0)
{
enemey.isDead = true;
break;
}
}
Console.WriteLine("Enemy is dead");
}
in this example, we are in a battle. Obviously we dont want the battle to prematurely end while the enemy is still alive (boolean isAlive would be a property on the enemy object) So we execute the "Attack" method until the enemy health is less than or equal to 0. If it is less than or equal to 0, isDeas is set to true on the enemy, then we execute "break;" to exit the battle while-loop. Obviously when the loop is broken that must mean the enemy has been defeated, so after the while loop comes the writeline to display the enemy is dead. Hopefully that made sense.
- 1
It tells the processor to continue with code execution after the loop (or switch statement)
- 1
Any loop
{
...
break; //on executing this it just comes 'out of loop' means it breaks or stops the loop execution further...
}
*out of loop..