200 Methods Chapter 6 76 77 } //

200 Methods Chapter 6 76 77 } // end method showOutputButton_Click 78 } Fig. 6.8 Demonstrating ref and out parameters. (Part 3 of 3.) Method showOutputButton_Click (lines 46 77) is an event handler that invokes methods SquareRef, SquareOut and Square when the user clicks the Show Output button. This method begins by initializing y to 5 and declaring (but not initializing) z. Lines 58 59 call methods SquareRef and SquareOut. Notice the syntax used for passing y and z in each case, we precede the argument either with refor with out. The output displays the values of y and z after the function calls. Notice that y has been changed to 25 and z has been set to 36. Finally, on lines 69 70 we call method Square. Arguments y and zboth are passed by value only copies of their values are passed to the method. As a result, the values of y and z remain 25 and 36, respectively. Common Programming Error 6.12 The ref and out arguments in a method call must match those specified in the method definition; otherwise, a syntax error occurs. Software Engineering Observation 6.10 By default, C# does not allow the programmer to choose whether to pass each argument by value or by reference. Value-type variables are passed by value. Objects are not passed to methods; rather, references to objects are passed to methods. The references themselves are passed by value. When a method receives a reference to an object, the method can manipulate the object directly, but the reference value cannot be changed (e.g., to refer to a new object). 6.10 Random-Number Generation We now take a brief and hopefully entertaining diversion into a popular programming application simulation and game playing. In this section and the next, we develop a nicely structured game-playing program that includes multiple methods. The program uses most of the control structures we have studied to this point and also introduces several new concepts. There is something in the air of a gambling casino that invigorates every type of person from the high rollers at the plush mahogany-and-felt craps tables to the quarter poppers at the one-armed bandits. It is the element of chance, the possibility that luck will convert a pocketful of money into a mountain of wealth. The element of chance can be introduced into computer applications with the Random class (located in namespace System).
In case you need quality webspace to host and run your web applications, try our personal web hosting services.

Leave a Reply