Training
Certifications
Books
Special Offers
Community




 
Microsoft® Visual C#® .NET Deluxe Learning Edition-Version 2003
Author Microsoft Corporation
Pages 672
Disk 6 Companion CD(s)
Level Beg/Int
Published 05/07/2003
ISBN 9780735619104
Price $119.99
To see this book's discounted price, select a reseller below.
 

More Information

About the Book
Table of Contents
Sample Chapter
Index
Related Series
Related Books
About the Author

Support: Book & CD

Rate this book
Barnes Noble Amazon Quantum Books

 


Chapter 3: Writing Methods and Applying Scope



Chapter 3 Writing Methods and Applying Scope

In Chapter 2, you learned how to declare variables, how to create expressions using operators, and how precedence and associativity control expressions containing multiple operators. In this chapter, you'll learn all about methods. You'll also learn how to use arguments and parameters to pass information to a method and how to return information from a method using return statements. Finally, you'll see how to step in and out of methods using the Microsoft Visual Studio .NET integrated debugger. This information is useful when you need to trace the execution of your methods because they do not work quite as you expected.

Declaring Methods

A method is a named sequence of statements. Each method has a name and a body. The method body contains the actual statements to be run when the method is called. The method name should be a meaningful identifier that indicates the overall purpose of the method (CalculateIncomeTax, for example). Most methods can be given some data, which they process, and can return information, which is usually the result of the processing. Methods are a fundamental and powerful mechanism.

Specifying the Method Declaration Syntax

The syntax of a Microsoft Visual C# method is as follows:

returnType  methodName parameterList 

    // method body statements go here 
}

  • The returnType is the name of a type and specifies what kind of information the method returns. This can be the name of any type, such as int or string. If you're writing a method that does not return a value, you must use the keyword void in place of the return type.
  • The methodName is the name used to call the method. Method names must follow the same identifier rules as variable names. For example, addValues is a valid method name, whereas add$Values is not valid. For now, you should use camelCase for method names, and you should make method names descriptive—start with a verb, such as displayCustomer.
  • The parameterList is optional and describes the types and names of the information that the method accepts. You write the parameters between the left and right parentheses as though you're declaring variables: name of the type, followed by the name of the parameter. If the method you're writing has two or more parameters, you must separate them with commas.
  • The method body statements are the lines of code that are run when the method is called. They are enclosed in an opening curly brace ({) and a closing curly brace (}).

Here's the definition of a method called addValues that returns an int and has two int parameters called lhs and rhs (short for left-hand side and right-hand side, respectively):

int addValues(int lhs, int rhs) 

    // ...
    // method body statements go here 
    // ...
}

Here's the definition of a method called showResult that does not return a value and has a single int parameter called answer:

void showResult(int answer)
{
    // ...
}

Notice that you use the keyword void to indicate that the method does not return anything.

Writing return Statements

If you want your method to return information (in other words, its return type is not void), you must write a return statement inside the method. You do this using the keyword return followed by an expression that calculates the returned value and a semicolon. The type of expression must be the same as the type specified by the function. In other words, if a function returns an int, the return statement must return an int; otherwise your program will not compile. Here is an example:

int addValues(int lhs, int rhs) 

    // ... 
    return lhs + rhs;
}

The return statement should be at the end of your method because it causes the method to finish. Any statements after the return statement will not be executed (though the compiler will warn you about this problem if you put statements after the return statement).

If you don't want your method to return information (its return type is void), you can use a variation of the return statement to cause an immediate exit from the method. You write the keyword return, immediately followed by a semicolon. For example:

void showResult(int answer) 

     
    if (...)
        return;
    

If your method does not return anything, you can also omit the return statement because the method will finish automatically when execution arrives at the closing curly brace at the end of the method. Although this practice is common, it is not always considered good style. Methods that return a value must contain a return statement.

In the following exercise, you will examine another version of the MathsOperators application from Chapter 2. This version has been improved by the careful use of some small methods.

Calling Methods

Methods exist to be called! You call a method by name to ask it to perform its task. If the method requires information (as specified by its parameters), you must supply the information as requested. If the method returns information (as specified by its return type), you should arrange to catch this information somehow.

Specifying the Method Call Syntax

The syntax of a C# method call is as follows:

methodName argumentList )

  • The methodName must exactly match the name of the method you're calling. Remember, C# is a case-sensitive language.
  • The argumentList supplies the optional information that the method accepts. You must supply an argument for each parameter, and the value of each argument must be compatible with the type of its corresponding parameter. If the method you're calling has two or more parameters, you must separate the arguments with commas.

Here is the addValues method:

int addValues(int lhs, int rhs) 

    // ... 
}

The addValues method has two int parameters, so you must call it with two comma-separated int arguments:

addValues(39, 3)     // okay

If you try to call addValues in some other way, you will probably not succeed:

addValues            // compile time error, no parentheses
addValues()          // compile time error, not enough arguments
addValues(39)        // compile time error, not enough arguments
addValues("39", "3") // compile time error, wrong types

The addValues method returns an int value. This int value can be used wherever an int value can be used. Consider this example:

result = addValues(39, 3);    // on right hand side of an assignment
showResult(addValues(39, 3)); // as argument to another method call

The following exercise continues using the MathsOperators application that was introduced in Chapter 2. This time you will examine some method calls.

Understanding Scope

You have seen that you can create a variable inside a method. The variable is created at the statement that defines it, and other statements in the same method that come afterwards can use the variable. In other words, a variable can be used only in certain places after it has been created. Once the method has finished, the variable disappears completely.

If an identifier can be used at a particular location in a program, the identifier is said to be in scope at that location. To put it another way, the scope of an identifier is simply the region of the program in which that identifier is usable. Scope applies to methods as well as variables. The scope of an identifier is linked to the location of the declaration that introduces the identifier into the program, as you'll now learn.

Creating Local Scope with a Method

The left and right curly braces that form the body of a method create a scope. Any variables you declare inside the body of a method are scoped to that method. These variables are called local variables because they are local to the method in which they are declared; they are not in scope in any other method. This arrangement means that you cannot use local variables to share information between methods. Consider this example:

class Example
{
    void method()
    {
        int variable;
        
    }
    void anotherMethod()
    {
        variable = 42; // compile time error
        
    }
}

Creating Class Scope with a Class

The left and right curly braces that form the body of a class also create a scope. Any "variables" you declare inside the body of a class (but not inside a method) are scoped to that class. As we saw in Chapter 2, the proper C# name for these variables is fields. In contrast to local variables, you can use fields to share information between methods. Here is an example:

class Example
{
    void method()
    {
        field = 42; // ok
        
    }
    void anotherMethod()
    {
        field = 42; // ok
        
    }
    int field;
}

Overloading Identifiers

If two identifiers have the same name and are declared in the same scope, you say that they are overloaded, that they overload each other. Most of the time an overloaded identifier is a bug that gets trapped as a compile-time error. For example, if you declare two local variables with the same name in the same method, you'll get a compile-time error. Similarly, if you declare two fields with the same name in the same class or two identical methods in the same class, you'll also get a compile-time error. This fact must seem hardly worth mentioning given that everything so far has turned out to be a compile-time error. Well, there is a way that you can overload an identifier, and that way is both useful and important.

You are allowed to overload a method, but only when the two methods have different parameters; that is, they have the same name but a different number of parameters, or the types of the parameters differ. This capability is allowed so that, when you call a method, you supply comma-separated arguments and the number and type of the arguments is used to select one of the overloaded methods.

The WriteLine method of the Console class is a good example of overloading. If you want to write a string to the console, you pass a string argument to WriteLine, and WriteLine(string s) is automatically called. If you want to write an int to the console, you pass an int argument to WriteLine and WriteLine(int i) is automatically called. Once again, the compiler sorts out the details for you.

At compile time, the compiler looks at the types of the arguments you are passing in and then calls the version of the named method that has a matching set of parameters. Here is an example:

static void Main()
{
    Console.WriteLine("The answer is ");
    Console.WriteLine(42);
}

Whereas you can overload the parameters of a method, you can't overload the return type of a method. In other words, you can't declare two methods with the same name that differ only in their return type. (The compiler is clever, but not that clever.)

Writing and Calling Methods

In the following exercises, you'll use the C# Method Wizard to help you write some methods that calculate how much a consultant would charge for a given number of consultancy days at a fixed daily rate. Next, you'll run these methods in a console application to get a feel for the program. Finally, you'll use the Visual Studio .NET debugger to step in and out of the method calls as they run.

In the final exercise, you'll use the Visual Studio .NET debugger to run your program in slow motion. You'll see when each method is called (this action is referred to as stepping into the method) and then see each return statement transfer control back to the caller (also known as stepping out of the method).

While you are stepping in and out of methods, you'll use the tools on the Debug toolbar. The Debug toolbar should appear automatically when you debug a program. If the toolbar does not appear, you can display it by pointing to Toolbars on the View menu and then clicking Debug.

Congratulations! You've successfully written and called methods and used the Visual Studio .NET debugger to step in and out of methods as they run.

If you want to continue to the next chapter

  • Keep Visual Studio .NET running and turn to Chapter 4.

If you want to exit Visual Studio .NET now

  • On the File menu, click Exit. If you see a Save dialog box, click Yes.

Chapter 3 Quick Reference

ToDo thisButton
Declare a methodWrite the method inside a class. For example:

int addValues(int lhs, int rhs)

{

}
 
Return a value from inside a methodWrite a return statement inside the method. For example:

return lhs + rhs; 
 
Return from a method before the end of the methodWrite a return statement inside the method. For example:

return;
 
Call a methodWrite the name of the method, together with any arguments between parentheses. For example:

addValues(39, 3);
 
Use the C# Method Wizard to help you write a methodIn Class View, right-click the name of the class. On the pop-up menu, point to Add, and then click Add Method.  
Display the Debug toolbarOn the View menu, point to Toolbars, and then click Debug. 
Step into a methodOn the Debug toolbar, click Step Into.

Or

On the Debug menu, click Step Into.

Click to view graphic
Click to view graphic

Step out of a methodOn the Debug toolbar, click Step Out.

Or

On the Debug menu, click Step Out.

Click to view graphic
Click to view graphic



Last Updated: March 11, 2003
Top of Page