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 taskmake 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 a parameterthe value of the parameter helps the car determine how fast to accelerate. Similarly, a method can require one or more parameters that represent additional information it needs to perform its task. A method call supplies valuescalled argumentsfor each of the method's parameters. For example, the Console.WriteLine method requires an argument that specifies the data to be displayed in a console window. Similarly, to make a deposit into a bank account, a Deposit method specifies a parameter that represents the deposit amount. When the Deposit method is called, an argument value 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 class GradeBook (Fig. 4.4) with a DisplayMessage method that displays the course name as part of the welcome message. (See the sample execution in Fig. 4.5.) The new DisplayMessage method requires a parameter that represents the course name to output.

Figure 4.4. Class declaration with a method that has a parameter.

(This item is displayed on page 136 in the print version)

 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 public void DisplayMessage( string courseName )
 9 {
10 Console.WriteLine( "Welcome to the grade book for
{0}!",
11 courseName );
12 } // end method DisplayMessage
13 } // end class GradeBook

Figure 4.5. Create GradeBook object and pass a string to its DisplayMessage method.

(This item is displayed on page 136 in the print version)

 1 // Fig. 4.5: GradeBookTest.cs
 2 // Create 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 {
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 string nameOfCourse = Console.ReadLine(); // read a line of text
17 Console.WriteLine(); // output a blank line
18
19 // call myGradeBook's DisplayMessage method
20 // and pass nameOfCourse as an argument
21 myGradeBook.DisplayMessage( nameOfCourse );
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!

Before discussing the new features of class GradeBook, let's see how the new class is used from the Main method of class GradeBookTest (Fig. 4.5). Line 12 creates an object of class GradeBook and 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, using Console method ReadLine to perform the input. The user types the course name and presses Enter to submit the course name to the application. Note that pressing Enter inserts a newline character at the end of the characters typed by the user. Method ReadLine reads characters typed by the user until the newline character is encountered, then returns a string containing the characters up to, but not including, the newline. The newline character is discarded.

Line 21 calls myGradeBook's DisplayMessage method. The variable nameOfCourse in parentheses is the argument that is passed to method DisplayMessage so that the method can perform its task. Variable nameOfCourse's value in Main becomes the value of method DisplayMessage's parameter courseName in line 8 of Fig. 4.4. When you execute this application, notice that method DisplayMessage outputs the name you type as part of the welcome message (Fig. 4.5).

Software Engineering Observation 4 1

Normally, objects are created with new. One exception is a string literal that is contained in quotes, such as "hello". String literals are references to string objects that are implicitly created by C#.

 

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's parameter list, which is located in the parentheses that follow the method name. The parameter list may contain any number of parameters, including none at all. Empty parentheses following the method name (as in Fig. 4.1, line 8) indicate that a method 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 string and the identifier courseName indicate that method DisplayMessage requires a string to 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 courseName to access the value. Lines 1011 of Fig. 4.4 display parameter courseName's value, using the {0} format item in WriteLine's first argument. Note that 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 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 will learn in subsequent chapters, an argument's type and its corresponding parameter's type are not always required to be identical.) In our example, the method call passes one argument of type string (nameOfCourse is declared as a string in line 16 of Fig. 4.5), and the method declaration specifies one parameter of type string (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.

Common Programming Error 4 1

A compilation error occurs if the number of arguments in a method call does not match the number of 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.

 

Updated UML Class Diagram for Class GradeBook

The UML class diagram of Fig. 4.6 models class GradeBook of Fig. 4.4. Like Fig. 4.4, this GradeBook class contains public operation DisplayMessage. However, this version of DisplayMessage has 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 parentheses following the operation name. The UML has several data types that are similar to the C# types. For example, UML types String and Integer correspond to C# types string and int, respectively. Unfortunately, the UML does not provide types that correspond 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. Class Gradebook's method DisplayMessage (Fig. 4.4) has a string parameter named courseName, so Fig. 4.6 lists courseName : string between the parentheses following DisplayMessage.

Figure 4.6. UML class diagram indicating that class GradeBook has a public DisplayMessage operation with a courseName parameter of type string.

 

Notes on using Directives

Notice the using directive in Fig. 4.5 (line 4). This indicates to the compiler that the application uses classes in the System namespace, like the Console class. Why do we need a using directive to use class Console, but not class GradeBook? There is a special relationship between 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. A using directive is not required when one class in a namespace uses another in the same namespacesuch as when class GradeBookTest uses class GradeBook. You will see in Section 9.14 how to declare your own namespaces with the namespace keyword. For simplicity, our examples in this chapter do not declare a namespace. Any classes that are not explicitly placed in a namespace are implicitly placed in the so-called global namespace.

Actually, the using directive in line 4 is not required if we always refer to class Console as System.Console, which includes the full namespace and class name. This is known as the class's fully qualified class name. For example, line 15 could be written as

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

Most C# programmers consider using fully qualified names to be cumbersome, and instead prefer to use using directives. The code generated by the Visual C# Form Designer uses fully qualified names.

Preface

Index

    Introduction to Computers, the Internet and Visual C#

    Introduction to the Visual C# 2005 Express Edition IDE

    Introduction to C# Applications

    Introduction to Classes and Objects

    Control Statements: Part 1

    Control Statements: Part 2

    Methods: A Deeper Look

    Arrays

    Classes and Objects: A Deeper Look

    Object-Oriented Programming: Inheritance

    Polymorphism, Interfaces & Operator Overloading

    Exception Handling

    Graphical User Interface Concepts: Part 1

    Graphical User Interface Concepts: Part 2

    Multithreading

    Strings, Characters and Regular Expressions

    Graphics and Multimedia

    Files and Streams

    Extensible Markup Language (XML)

    Database, SQL and ADO.NET

    ASP.NET 2.0, Web Forms and Web Controls

    Web Services

    Networking: Streams-Based Sockets and Datagrams

    Searching and Sorting

    Data Structures

    Generics

    Collections

    Appendix A. Operator Precedence Chart

    Appendix B. Number Systems

    Appendix C. Using the Visual Studio 2005 Debugger

    Appendix D. ASCII Character Set

    Appendix E. Unicode®

    Appendix F. Introduction to XHTML: Part 1

    Appendix G. Introduction to XHTML: Part 2

    Appendix H. HTML/XHTML Special Characters

    Appendix I. HTML/XHTML Colors

    Appendix J. ATM Case Study Code

    Appendix K. UML 2: Additional Diagram Types

    Appendix L. Simple Types

    Index



    Visual C# How to Program
    Visual C# 2005 How to Program (2nd Edition)
    ISBN: 0131525239
    EAN: 2147483647
    Year: 2004
    Pages: 600

    Flylib.com © 2008-2020.
    If you may any questions please contact us: flylib@qtcs.net