Methods: A Deeper Look
Chapter 7 of Visual C# How to Program, 6/e
© 2018 Pearson Education, Ltd. All Rights Reserved.
© 2018 Pearson Education, Ltd. All Rights Reserved.
© 2018 Pearson Education, Ltd. All Rights Reserved.
© 2018 Pearson Education, Ltd. All Rights Reserved.
© 2018 Pearson Education, Ltd. All Rights Reserved.
© 2018 Pearson Education, Ltd. All Rights Reserved.
7.2 Packaging Code in C#
So far, we’ve used properties, methods and classes to
package code.
C# apps are written by combining your properties, methods
and classes with predefined properties, methods and
classes available in the .NET Framework Class Library and
in other class libraries.
Related classes are often grouped into namespaces and
compiled into class libraries so that they can be reused in
other apps.
© 2018 Pearson Education, Ltd. All
Rights Reserved.
© 2018 Pearson Education, Ltd. All Rights Reserved.
7.2.1 Modularizing Programs
Methods allow you to modularize an app by separating its
tasks into reusable units.
Motivations for modularizing an app with methods
Software reuse—existing methods can be used as building blocks
to create new apps.
Avoid repeating code.
Making programs easier to test, debug and maintain
Dividing an app into meaningful methods makes the app
easier to debug and maintain.
© 2018 Pearson Education, Ltd. All
Rights Reserved.
© 2018 Pearson Education, Ltd. All Rights Reserved.
7.2.2 Calling Methods
As you know, a method is invoked by a method call, and
when the called method completes its task, it returns
control and possibly a result to its caller.
An analogy to the method-call-and-return structure is the
hierarchical form of management (Fig. 7.1).
The boss method does not know how the worker method performs its designated
tasks.
The worker may also call other worker methods.
This hiding of implementation details promotes good software
engineering.
© 2018 Pearson Education, Ltd. All
Rights Reserved.
© 2018 Pearson Education, Ltd. All Rights Reserved.
7.3 static Methods, static Variables and Class Math
A method that applies to the class as a whole is known as a static
method.
To declare a method as static, place the keyword static before the
return type in the method’s declaration.
You call any static method by specifying the name of the class in
which the method is declared, followed by the member access (.)
operator and the method name.
© 2018 Pearson Education, Ltd. All
Rights Reserved.
7.3.1 Math Class Methods
Class Math provides a collection of static methods that enable you to
perform common mathematical calculations.
You do not need to create a Math object before calling method Sqrt.
Method arguments may be constants, variables or expressions.
© 2018 Pearson Education, Ltd. All
Rights Reserved.
7.3.1 Math Class Methods
Figure 7.2 summarizes several Math class methods. In the figure, x and
y are of type double.
© 2018 Pearson Education, Ltd. All
Rights Reserved.
© 2018 Pearson Education, Ltd. All Rights Reserved.
© 2018 Pearson Education, Ltd. All Rights Reserved.
7.3 static Methods, static Variables and Class Math
(Cont.)
When objects of a class containing static variables are created, all the
objects of that class share one copy of the class’s static variables.
Together the static variables and instance variables represent the fields
of a class.
© 2018 Pearson Education, Ltd. All
Rights Reserved.
© 2018 Pearson Education, Ltd. All Rights Reserved.
7.3.3 Why Is Main Declared static?
Main is sometimes called the app’s entry point.
Declaring Main as static allows the execution
environment to invoke Main without creating an instance of
the class.
© 2018 Pearson Education, Ltd. All
Rights Reserved.
7.3.4 Additional Comments about Main
You can place a Main method in every class you declare.
Some programmers take advantage of this to build a small test app into
each class they declare.
If you declare more than one Main method among the classes of your
project, you’ll need to indicate to the IDE which one you would like to
be the app’s entry point:
With the project open in Visual Studio, select Project > [ProjectName]
Properties... (where [ProjectName] is the name of your project).
Select the class containing the Main method that should be the entry point from
the Startup object list box.
© 2018 Pearson Education, Ltd. All
Rights Reserved.
7.4 Methods with Multiple Parameters
Fig. 7.3 declares method Maximum which determines and returns the
largest of three double values.
© 2018 Pearson Education, Ltd. All
Rights Reserved.
© 2018 Pearson Education, Ltd. All Rights Reserved.
© 2018 Pearson Education, Ltd. All Rights Reserved.
© 2018 Pearson Education, Ltd. All Rights Reserved.
7.4.1 Keyword static
Method Maximum’s declaration begins with keyword static, which
enables the Main method (another static method) to call Maximum as
shown in line 19 without creating an object of class MaximumFinder
and without qualifying the method name with the class name
MaximumFinder.
Static methods in the same class can call each other directly.
© 2018 Pearson Education, Ltd. All Rights Reserved.
7.4.2 Method Maximum
When a method has more than one parameter, the parameters are
specified as a comma-separated list.
Each argument must be consistent with the type of the corresponding
parameter.
When program control returns from a method, that method’s
parameters are no longer accessible in memory.
Methods can return at most one value.
© 2018 Pearson Education, Ltd. All Rights Reserved.
7.4 Methods with Multiple Parameters (Cont.)
When to Declare Variables as Fields of a Class
Variables should be declared as fields of a class only if they are
required for use in more than one method or if the app needs to save
their values between calls to the class’s methods.
© 2018 Pearson Education, Ltd. All Rights Reserved.
© 2018 Pearson Education, Ltd. All Rights Reserved.
7.4.3 Assembling strings with Concatenation
string concatenation allows you to combine strings using + .
When one of the + operator’s operands is a string, the other is
implicitly converted to a string, then the two are concatenated.
If a bool is concatenated with a string, the bool is converted to the
string "True" or "False".
Every object has a ToString method that returns a string
representation of that object.
When an object is concatenated with a string, the object’s ToString
method is called implicitly to obtain the string representation of the
object. If the object is null, an empty string is written.
© 2018 Pearson Education, Ltd. All Rights Reserved.
© 2018 Pearson Education, Ltd. All Rights Reserved.
7.4.6 Implementing Method Maximum by Reusing
Method Math.Max
The entire body of our maximum method could also be implemented
with nested calls to Math.Max, as follows:
return Math.Max(x, Math.Max(y, z));
Before any method can be called, the .NET runtime evaluates all its
arguments to determine their values.
Math.Max(y, z) is evaluated first, then the result is passed as the
second argument to the other call to Math.Max
© 2018 Pearson Education, Ltd. All
Rights Reserved.
7.5 Notes on Using Methods
Three ways to call a method:
Using a method name by itself to call a method of the same class
Maximum(number1, number2, number3)
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
account1.Deposit(depositAmount)
Using the class name and the member-access operator (.) to call a
static method of a class
Console.ReadLine()
Math.Sqrt(900.0) © 2018 Pearson Education, Ltd. All
Rights Reserved.
7.5 Notes on Using Methods
Three
ways to return control to the statement that calls a
method.
Reaching the end of the method.
A return statement without a value.
A return statement with a value.
© 2018 Pearson Education, Ltd. All
Rights Reserved.
© 2018 Pearson Education, Ltd. All Rights Reserved.
© 2018 Pearson Education, Ltd. All Rights Reserved.
© 2018 Pearson Education, Ltd. All Rights Reserved.
7.5 Notes on Using Methods (cont.)
A static method or property can call only other static methods or
properties of the same class directly 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.
© 2018 Pearson Education, Ltd. All
Rights Reserved.
© 2018 Pearson Education, Ltd. All Rights Reserved.
7.10 Scope of Declarations
The scope of a declaration is the portion of the app that can refer to the
declared entity by its unqualified name.
The basic scope rules are as follows:
The scope of a parameter declaration is the body of the method in which the
declaration appears.
The scope of a local-variable declaration is from the point at which the
declaration appears to the end of the block containing the declaration.
The scope of a non-static method, property or field of a class is the entire body of
the class.
If a local variable or parameter in a method has the same name as a
field, the field is hidden until the block terminates (scope hole).
© 2018 Pearson Education, Ltd. All
Rights Reserved.
© 2018 Pearson Education, Ltd. All Rights Reserved.
© 2018 Pearson Education, Ltd. All Rights Reserved.
© 2018 Pearson Education, Ltd. All Rights Reserved.
© 2018 Pearson Education, Ltd. All Rights Reserved.
© 2018 Pearson Education, Ltd. All Rights Reserved.
7.12 Method Overloading
Methods of the same name can be declared in the same class, or
overloaded, as long as they have different sets of parameters.
When an overloaded method is called, the C# compiler selects the
appropriate method by examining the number, types and order of the
arguments in the call.
Method overloading is used to create several methods with the same
name that perform the same tasks, but on different types or numbers
of arguments.
© 2018 Pearson Education, Ltd. All
Rights Reserved.
7.12.1 Declaring Overloaded Methods
Class MethodOverload (Fig. 7.10) includes two overloaded versions of
a method called Square.
Although these methods have the same name and similar parameter
lists and bodies, you can think of them simply as different methods.
It may help to think of the method names as “Square of int” and
“Square of double,” respectively
© 2018 Pearson Education, Ltd. All
Rights Reserved.
© 2018 Pearson Education, Ltd. All Rights Reserved.
© 2018 Pearson Education, Ltd. All Rights Reserved.
7.12.2 Distinguishing Between Overloaded Methods
The compiler distinguishes overloaded methods by their signature—a
combination of the method’s name and the number, types and order of
its parameters.
© 2018 Pearson Education, Ltd. All
Rights Reserved.
7.12.3 Return Types of Overloaded Methods
Method calls cannot be distinguished by return type.
If in a class you define overloaded methods with the following headers:
int Square(int x)
double Square(int x)
The compiler generates the following error for the second Square
method:
Type 'MethodOverloadError' already defines a member called 'Square' with the
same parameter types
© 2018 Pearson Education, Ltd. All
Rights Reserved.
© 2018 Pearson Education, Ltd. All Rights Reserved.
7.13 Optional Parameters
Methods can have optional parameters that allow the calling method to
vary the number of arguments to pass.
An optional parameter specifies a default value that’s assigned to the
parameter if the optional argument is omitted.
You can create methods with one or more optional parameters.
All optional parameters must be placed to the right of the method’s
non-optional parameters.
© 2018 Pearson Education, Ltd. All
Rights Reserved.
© 2018 Pearson Education, Ltd. All Rights Reserved.
7.13 Optional Parameters (Cont.)
When a parameter has a default value, the caller has the option of
passing that particular argument.
For example, the method header
static int Power(int baseValue, int exponentValue = 2)
specifies an optional second parameter.
Any call to Power must pass at least an argument for the parameter
baseValue, or a compilation error occurs.
© 2018 Pearson Education, Ltd. All
Rights Reserved.
7.13 Optional Parameters (Cont.)
Optionally, a second argument (for the exponentValue parameter)
can be passed to Power. Consider the following calls to Power:
Power()
Power(10)
Power(10, 3)
The first generates a compilation error because this method requires a
minimum of one argument.
The second is valid because one argument (10) is being passed—the
optional exponentValue is not specified in the method call.
The last call is also valid—10 is passed as the required argument and 3
is passed as the optional argument.
© 2018 Pearson Education, Ltd. All
Rights Reserved.
© 2018 Pearson Education, Ltd. All Rights Reserved.
© 2018 Pearson Education, Ltd. All Rights Reserved.
7.15 C# 6 Expression Bodied Methods
If the expression to the right of => does not have a value (e.g., a call to a
method that returns void), the expression-bodied method must return
void.
Similarly, a read-only property can be implemented as an expression-
bodied property.
The following reimplements the IsNoFaultState property in Fig.
6.11 to return the result of a logical expression:
public bool IsNoFaultState =>
State == "MA" || State == "NJ" || State == "NY" || State == "PA";
© 2018 Pearson Education, Ltd. All
Rights Reserved.
7.16 Recursion
A recursive method is a method that calls itself.
A recursive method is capable of solving only the base case(s).
Each method call divides the problem into two conceptual pieces: a
piece that the method knows how to do and a recursive call, or
recursion step that solves a smaller problem.
A sequence of returns ensues until the original method call returns the
result to the caller.
© 2018 Pearson Education, Ltd. All
Rights Reserved.
© 2018 Pearson Education, Ltd. All Rights Reserved.
© 2018 Pearson Education, Ltd. All Rights Reserved.
© 2018 Pearson Education, Ltd. All Rights Reserved.
© 2018 Pearson Education, Ltd. All Rights Reserved.