- 7.1 Introduction
- 7.2 Packaging Code in C#
- 7.3 static Methods, static Variables and Class Math
- 7.4 Methods with Multiple Parameters
- 7.5 Notes on Using Methods
- 7.6 Argument Promotion and Casting
- 7.7 The .NET Framework Class Library
- 7.8 Case Study: Random-Number Generation
- 7.9 Case Study: A Game of Chance; Introducing Enumerations
- 7.10 Scope of Declarations
- 7.11 Method-Call Stack and Activation Records
- 7.12 Method Overloading
- 7.13 Optional Parameters
- 7.14 Named Parameters
- 7.15 C# 6 Expression-Bodied Methods and Properties
- 7.16 Recursion
- 7.17 Value Types vs. Reference Types
- 7.18 Passing Arguments By Value and By Reference
- 7.19 Wrap-Up
7.5 Notes on Using Methods
Three Ways to Call a Method
You’ve seen three ways to call a method:
Using a method name by itself to call a method of the same class—as in line 19 of Fig. 7.2, which calls Maximum(number1, number2, number3) from Main.
Using a reference to an object, followed by the member-access operator (.) and the method name to call a non-static method of the referenced object—as in line 23 of Fig. 4.12, which called account1.Deposit(depositAmount) from the Main method of class AccountTest.
Using the class name and the member-access operator (.) to call a static method of a class—as in lines 12, 14 and 16 of Fig. 7.2, which each call Console.ReadLine(), or as in Math.Sqrt(900.0) in Section 7.3.
Three Ways to Return from a Method
You’ve seen three ways to return control to the statement that calls a method:
Reaching the method-ending right brace in a method with return type void.
When the following statement executes in a method with return type void
return;
When a method returns a result with a statement of the following form in which the expression is evaluated and its result (and control) are returned to the caller:
return expression;
static Members Can Access Only the Class’s Other static Members Directly
A static method or property can call only other static methods or properties of the same class directly (i.e., using the method name by itself) and can manipulate only static variables in the same class directly. To access a class’s non-static members, a static method or property must use a reference to an object of that class. Recall that static methods relate to a class as a whole, whereas non-static methods are associated with a specific object (instance) of the class and may manipulate the instance variables of that object (as well as the class’s static members).
Many objects of a class, each with its own copies of the instance variables, may exist at the same time. Suppose a static method were to invoke a non-static method directly. How would the method know which object’s instance variables to manipulate? What would happen if no objects of the class existed at the time the non-static method was invoked?