Declaring a Method with a Parameter

Một phần của tài liệu Visual C 2012 How to Program _ www.bit.ly/taiho123 (Trang 154 - 157)

2. When the app executes, another compiler (known as the just-in-time compiler

4.4 Declaring a Method with a Parameter

4.4 Declaring a Method with a Parameter

In our car analogy from Section 4.2, we discussed the fact that pressing a car’s gas pedal sends a message to the car to perform a task—make the car go faster. But how fast should the car accelerate? As you know, the farther down you press the pedal, the faster the car accelerates. So the message to the car actually includes both the task to be performed and additional information that helps the car perform the task. This additional information is known as aparameter—the value of the parameter helps the car determine how fast to ac- celerate. Similarly, a method can require one or more parameters that represent additional information it needs to perform its task. A method call supplies values—called argu- ments—for each of the method’s parameters. For example, theConsole.WriteLinemeth- od requires an argument that specifies the data to be displayed in a console window.

Similarly, to make a deposit into a bank account, aDepositmethod specifies a parameter that represents the deposit amount. When theDepositmethod is called, an argument val- ue representing the deposit amount is assigned to the method’s parameter. The method then makes a deposit of that amount, by increasing the account’s balance.

Our next example declares classGradeBook(Fig. 4.4) with aDisplayMessagemethod that displays the course name as part of the welcome message. (See the sample execution in Fig. 4.5.) The newDisplayMessagemethod requires a parameter that represents the course name to output.

1 // Fig. 4.4: GradeBook.cs

2 // Class declaration with a method that has a parameter.

3 using System;

4

5 public class GradeBook 6 {

7 // display a welcome message to the GradeBook user 8

9 {

10 Console.WriteLine( "Welcome to the grade book for\n{0}!",

11 courseName );

12 } // end method DisplayMessage 13 } // end class GradeBook

Fig. 4.4 | Class declaration with a method that has a parameter.

1 // Fig. 4.5: GradeBookTest.cs

2 // Create a GradeBook object and pass a string to 3 // its DisplayMessage method.

4 using System;

5

6 public class GradeBookTest 7 {

8 // Main method begins program execution 9 public static void Main( string[] args )

10 {

Fig. 4.5 | CreateGradeBookobject and pass astringto itsDisplayMessagemethod. (Part 1 of 2.)

public void DisplayMessage( string courseName )

Before discussing the new features of classGradeBook, let’s see how the new class is used from theMainmethod of classGradeBookTest(Fig. 4.5). Line 12 creates an object of classGradeBookand assigns it to variable myGradeBook. Line 15 prompts the user to enter a course name. Line 16 reads the name from the user and assigns it to the variable

nameOfCourse, usingConsolemethodReadLineto perform the input. The user types the course name and pressesEnterto submit the course name to the app. PressingEnterinserts a newline character at the end of the characters typed by the user. MethodReadLinereads characters typed by the user until the newline character is encountered, then returns a

stringcontaining the characters up to, but not including, the newline. The newline char- acter isdiscarded.

Line 21 callsmyGradeBook’sDisplayMessagemethod. The variablenameOfCoursein parentheses is the argument that’s passed to methodDisplayMessageso that the method can perform its task. VariablenameOfCourse’s value inMain becomes the value of method

DisplayMessage’s parametercourseNamein line 8 of Fig. 4.4. When you execute this app, notice that methodDisplayMessageoutputs as part of the welcome message the name you type (Fig. 4.5).

More on Arguments and Parameters

When you declare a method, you must specify in the method’s declaration whether the method requires data to perform its task. To do so, you place additional information in the method’sparameter list, which is located in the parentheses that follow the method 11 // create a GradeBook object and assign it to myGradeBook

12 GradeBook myGradeBook = new GradeBook();

13

14 // prompt for and input course name

15 Console.WriteLine( "Please enter the course name:" );

16

17 Console.WriteLine(); // output a blank line 18

19 // call myGradeBook's DisplayMessage method 20 // and pass nameOfCourse as an argument 21

22 } // end Main

23 } // end class GradeBookTest

Please enter the course name:

CS101 Introduction to C# Programming Welcome to the grade book for

CS101 Introduction to C# Programming!

Software Engineering Observation 4.1

Normally, objects are created withnew. One exception is a string literal that’s contained in quotes, such as"hello". String literals arestringobjects that are implicitly created by C# the first time they appear in the code.

Fig. 4.5 | CreateGradeBookobject and pass astringto itsDisplayMessagemethod. (Part 2 of 2.)

string nameOfCourse = Console.ReadLine(); // read a line of text

myGradeBook.DisplayMessage( nameOfCourse );

4.4 Declaring a Method with a Parameter 115

name. The parameter list may contain any number of parameters, including none at all.

Each parameter is declared as a variable with a type and identifier in the parameter list.

Empty parentheses following the method name (as in Fig. 4.1, line 8) indicate that a meth- od does not require any parameters. In Fig. 4.4,DisplayMessage’s parameter list (line 8) declares that the method requires one parameter. Each parameter must specify a type and an identifier. In this case, the type stringand the identifier courseName indicate that methodDisplayMessagerequires astringto perform its task. At the time the method is called, the argument value in the call is assigned to the corresponding parameter (in this case, courseName) in the method header. Then, the method body uses the parameter

courseNameto access the value. Lines 10–11 of Fig. 4.4 display parametercourseName’s value, using the{0}format item inWriteLine’s first argument. The parameter variable’s name (Fig. 4.4, line 8) can be the same or different from the argument variable’s name (Fig. 4.5, line 21).

A method can specify multiple parameters by separating each parameter from the next with a comma. The number of arguments in a method call must match the number of required parameters in the parameter list of the called method’s declaration. Also, the types of the arguments in the method call must be consistent with the types of the corresponding parameters in the method’s declaration. (As you’ll learn in subsequent chapters, an argu- ment’s type and its corresponding parameter’s type arenotalways required to be identical.) In our example, the method call passes one argument of typestring (nameOfCourseis declared as astring in line 16 of Fig. 4.5), and the method declaration specifies one parameter of typestring(line 8 in Fig. 4.4). So the type of the argument in the method call exactly matches the type of the parameter in the method header.

Updated UML Class Diagram for ClassGradeBook

The UML class diagram of Fig. 4.6 models classGradeBookof Fig. 4.4. Like Fig. 4.4, this

GradeBook class contains public operation DisplayMessage. However, this version of

DisplayMessagehas a parameter. The UML models a parameter a bit differently from C#

by listing the parameter name, followed by a colon and the parameter type in the paren- theses following the operation name. The UML has several data types that are similar to

Common Programming Error 4.1

A compilation error occurs if the number of arguments in a method call does not match the number of required parameters in the method declaration.

Common Programming Error 4.2

A compilation error occurs if the types of the arguments in a method call are not consistent with the types of the corresponding parameters in the method declaration.

Fig. 4.6 | UML class diagram indicating that classGradeBookhas a publicDisplayMessage

operation with acourseNameparameter of typestring.

GradeBook + DisplayMessage( courseName : string )

the C# types. For example, UML types String and Integer correspond to C# types

stringandint, respectively. Unfortunately, the UML does not provide types that corre- spond to every C# type. For this reason, and to avoid confusion between UML types and C# types,we use only C# types in our UML diagrams. ClassGradebook’s methodDisplay-

Message(Fig. 4.4) has astringparameter namedcourseName, so Fig. 4.6 lists the param- etercourseName : stringbetween the parentheses followingDisplayMessage.

Notes onusingDirectives

Notice theusingdirective in Fig. 4.5 (line 4). This indicates to the compiler that the app uses classes in theSystemnamespace, like theConsoleclass. Why do we need ausingdi- rective to use classConsole, but not classGradeBook? There’s a special relationship be- tween classes that are compiled in the same project, like classes GradeBook and

GradeBookTest. By default, such classes are considered to be in the same namespace. Aus-

ingdirective is not required when one class in a namespace uses another in the same namespace—such as when classGradeBookTestuses classGradeBook. For simplicity, our examples in this chapter do not declare a namespace. Any classes that are notexplicitly placed in a namespace areimplicitlyplaced in the so-calledglobal namespace.

Actually, theusingdirective in line 4 is not required if we always refer to classCon-

sole as System.Console, which includes the full namespace and class name. This is known as the class’sfully qualified class name. For example, line 15 could be written as

Most C# programmers consider using fully qualified names to be cumbersome, and in- stead prefer to useusingdirectives.

Một phần của tài liệu Visual C 2012 How to Program _ www.bit.ly/taiho123 (Trang 154 - 157)

Tải bản đầy đủ (PDF)

(1.020 trang)