|
Chapter 3: Writing Methods and Applying Scope
Chapter 3 Writing Methods and Applying ScopeIn 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 MethodsA 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 SyntaxThe syntax of a Microsoft Visual C# method is as follows:
returnType methodName ( parameterList )
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) 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 StatementsIf 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) 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 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 MethodsMethods 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 SyntaxThe syntax of a C# method call is as follows:
methodName ( argumentList )
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 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 The following exercise continues using the MathsOperators application that was introduced in Chapter 2. This time you will examine some method calls.
Understanding ScopeYou 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 MethodThe 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
Creating Class Scope with a ClassThe 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
Overloading IdentifiersIf 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() 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 MethodsIn 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
If you want to exit Visual Studio .NET now
Chapter 3 Quick Reference
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||