Home > Articles

This chapter is from the book

This chapter is from the book

7.5 Notes on Using Methods

Three Ways to Call a Method

You’ve seen three ways to call a method:

  1. 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.

  2. 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.

  3. 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?

  • + Share This
  • 🔖 Save To Your Account