Flow-control structures: Difference between revisions

Added C#
m (→‎{{header|REBOL}}: Remove vanity tags)
(Added C#)
Line 401:
<< "inside foobar(). Thus this catch-all block never gets invoked.\n";
}
}</lang>
 
=={{header|C sharp}}==
===return===
terminates the function and returns control to the caller.
<lang csharp>int GetNumber() {
return 5;
}</lang>
===throw===
throws (or rethrows) an exception. Control is transferred to the nearest catch block capable of catching the exception.<br/>
A <code>finally</code> block is always executed before control leaves the <code>try</code> block.
<lang csharp>try {
if (someCondition) {
throw new Exception();
}
} catch (Exception ex) {
LogException(ex);
throw;
} finally {
cleanUp();
}</lang>
===yield return and yield break===
In a generator method, <code>yield return</code> causes the method to return elements one at a time. To make this work, the compiler creates a state machine behind the scenes. <code>yield break</code> terminates the iteration.
<lang csharp>public static void Main() {
foreach (int n in Numbers(i => i >= 2) {
Console.WriteLine("Got " + n);
}
}
 
IEnumerable<int> Numbers(Func<int, bool> predicate) {
for (int i = 0; ; i++) {
if (predicate(i)) yield break;
Console.WriteLine("Yielding " + i);
yield return i;
}
}
</lang>
{{out}}
<pre>
Yielding 0
Got 0
Yielding 1
Got 1</pre>
===await===
is used to wait for an asynchronous operation (usually a Task) to complete. If the operation is already completed when <code>await</code> is encountered, the method will simply continue to execute. If the operation is not completed yet, the method will be suspended. A continuation will be set up to execute the rest of the method at a later time. Then, control will be returned to the caller.
<lang csharp>async Task DoStuffAsync() {
DoSomething();
await someOtherTask;//returns control to caller if someOtherTask is not yet finished.
DoSomethingElse();
}
</lang>
===break and continue===
<code>continue</code> causes the closest enclosing loop to skip the current iteration and start the next iteration immediately.<br/>
<code>break</code> terminates the closest enclosing loop or <code>switch</code> statement. Control is passed to the statement that follows the terminated statement.
===<code>goto</code>===
<code>goto Label;</code> will cause control to jump to the statement with the corresponding label. This can be a <code>case</code> label inside a <code>switch</code>.<br/>
Because the label must be in scope, <code>goto</code> cannot jump inside of a loop.
<lang csharp>while (conditionA) {
for (int i = 0; i < 10; i++) {
if (conditionB) goto NextSection;
DoSomething(i);
}
NextSection: DoOtherStuff();
}</lang>
 
196

edits