C Sharp

The return Statement

The return statement has two functions. It specifies a value to be returned to the caller of the currently executed code (when the current code is not defined as returning void), and it causes an immediate return to the caller. The return statement is defined with the following syntax: -

return [ return-expression ] -

When the compiler encounters a method's return statement that specifies a return-expression, it evaluates whether the return-expression can be implicitly converted into a form compatible with the current method's defined return value. It's the result of that conversion that is passed back to the caller.

When using the return statement with exception handling, you have to be sure that you understand some rules. If the return statement is a try block that contains an associated finally block, control is actually passed to the first line of the finally block, and when that block of code finishes, control is passed back to the caller. If the try block is nested in another try block, control will continue back up the chain in this fashion until the final finally block has executed.

Summary

The C# conditional statements enable you to control program flow. The three different categories of flow statements include the selection statements, such as if and switch, the iteration statements (while, for,and foreach) and the different jump statements (break, continue, goto,and return). Determining the best statements to use based on the material in this chapter will help you write better structured and more maintainable applications.