These are used to transfer control to another part of the program, usually within loops or methods.
📌 1. break
- Exits the current loop or switch statement immediately.
for (int i = 0; i < 10; i++)
{
if (i == 5)
break; // exits the loop
Console.WriteLine(i);
}
// Output: 0 1 2 3 4
- Commonly used in
for
,while
,do-while
, andswitch
.
📌 2. continue
- Skips the rest of the current iteration and moves to the next iteration of the loop.
for (int i = 0; i < 5; i++)
{
if (i == 2)
continue; // skips printing 2
Console.WriteLine(i);
}
// Output: 0 1 3 4
- Does not exit the loop, just skips to the next iteration.
📌 3. goto
-
Jumps to a labeled statement.
-
Rarely used in modern code because it can make code hard to read.
int i = 0;
start:
Console.WriteLine(i);
i++;
if (i < 5) goto start;
- Output: 0 1 2 3 4
✅ Tip: Use only for special cases; loops are usually better.
📌 4. return
- Exits a method immediately, optionally returning a value.
int Add(int a, int b)
{
if (a < 0 || b < 0)
return -1; // early exit
return a + b;
}
Console.WriteLine(Add(5, 3)); // 8
Console.WriteLine(Add(-1, 3)); // -1
- Also used in
void
methods to exit early.
📌 5. throw
-
Exits the current method by throwing an exception.
-
Transfers control to the nearest
catch
block or terminates the program if unhandled.
void CheckAge(int age)
{
if (age < 0)
throw new ArgumentException("Age cannot be negative");
Console.WriteLine("Valid age");
}
CheckAge(25); // Valid age
CheckAge(-5); // Throws exception
📌 6. yield return / yield break (special jump for iterators)
-
yield return
→ returns the next element in an iterator. See What is Yield Return -
yield break
→ exits the iterator method early.
IEnumerable<int> GetNumbers()
{
for (int i = 0; i < 5; i++)
{
if (i == 3)
yield break; // stop iteration
yield return i;
}
}
foreach (var n in GetNumbers())
Console.WriteLine(n); // 0 1 2
📌 7. Summary Table
Jump Statement | Purpose | Use Case |
---|---|---|
break | Exit loop or switch | Stop early |
continue | Skip current iteration of loop | Skip unwanted steps |
goto | Jump to a labeled statement | Rare, specific jumps |
return | Exit a method, optionally with value | Early method exit |
throw | Exit method by raising an exception | Error handling |
yield return | Return next element in iterator | Custom iteration |
yield break | Stop iteration | End iterator early |
✅ Tip:
-
break
andcontinue
are loop control statements. -
return
andthrow
are method control statements. -
goto
is rarely needed, usually loops or functions handle jumps better. -
yield return/yield break
are advanced, iterator-specific.