Here is what I currently use to break out of a double loop and proceed with DoStuff():
foreach (var enemyUnit in nearbyEnemyUnits) {
var skip = false;
foreach (var ownUnit in ownUnits) {
if (ownUnit.EngagedTargetTag == enemyUnit.tag) {
skip = true;
break;
}
}
if (skip) continue;
DoStuff(enemyUnit);
}
The whole "defining a temporary boolean variable to check for a skip" seems very hacky to me. In a language like Go I can use labels to break out of loops, or even make the inner loop part of a clojure. What is the best way to do this in C#?
I've been doing it like the above example for the longest time and feel like there must be a better way - almost ashamed to ask at this point.
Thank you
You could use a goto, anonymous method, wrap it in a method, or C#7 you could use a local function
static void Main(string[] args)
{
void localMethod()
{
foreach (var enemyUnit in nearbyEnemyUnits)
foreach (var ownUnit in ownUnits)
if (ownUnit.EngagedTargetTag == enemyUnit.tag)
return;
}
localMethod();
}
Additional Resources
goto (C# Reference)
Anonymous Methods (C# Programming Guide)
Local functions (C# Programming Guide)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With