Home > Articles > Programming > C#

  • Print
  • + Share This
This chapter is from the book

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 a parameter—the 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 values—called arguments—for 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.

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

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\n{0}!",
11           courseName );
12     }  // end method DisplayMessage
13  }  // end class GradeBook

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

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     {
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

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. 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's 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 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'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. 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 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 10–11 of Fig. 4.4 display parameter courseName's value, using the {0} format item in WriteLine'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 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.

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 Display-Message (Fig. 4.4) has a string parameter named courseName, so Fig. 4.6 lists the parameter courseName : string between the parentheses following DisplayMessage.

Fig. 4.6

Fig. 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's 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 namespace—such as when class GradeBookTest uses class GradeBook. 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.

  • + Share This
  • 🔖 Save To Your Account