Methods

advertisement
Methods
Implicit Argument Conversions
An important feature of argument passing is implicit
argument conversion—in which Visual Basic converts an
argument’s value to the type that the method expects to
receive in its corresponding parameter.
Widening and narrowing conversions are supported.
A widening conversion occurs when an argument is
converted to a parameter of another type that can hold
more data, whereas a narrowing conversion occurs when
there’s potential for data loss during the conversion (that
is, a conversion to a parameter of a type that holds a
smaller amount of data).
Implicit Conversions
Byte --> Byte, Short, Integer, Long, Decimal, Single,
Double
Short --> Short, Integer, Long, Decimal, Single,
Double
Integer --> Integer, Long, Decimal, Single, Double
Long --> Long, Decimal, Single, Double
Decimal --> Decimal, Single, Double
Single --> Single, Double
Double --> Double
Implicit Argument Conversions
Conversions also occur for expressions containing values of
two or more types.
In such expressions, the values’ original types are maintained,
while temporary copies of the values are converted for use in
the expression.
Each value is converted to the “widest” type in the expression
(that is, widening conversions are made until the values are of
the same type as the “widest” type).
For example, if doubleValue is of type Double and integerValue
is of type Integer, when the expression
doubleValue + integerValue
is evaluated, the value of integerValue is converted to type Double
(the widest type in the expression), then added to doubleValue,
producing a Double result.
Option Strict and Data-Type
Conversions
Option Explicit
◦ Option Explicit—which is set to On by default requires you to declare all
variables before they’re used in a program.
◦ This eliminates various errors.
◦ For example, when Option Explicit is set to Off, the compiler interprets
misspelled variable names as new variables and implicitly declares them to be
of type Object.
◦ It’s recommended that you leave this option set to On.
Option Strict and Data-Type
Conversions
Option Strict
◦ A second option, which defaults to Off, is Option Strict.
◦ This option increases program clarity and reduces debugging time.
◦ When set to On, Option Strict causes the compiler to check all conversions
and requires you to perform explicit conversions—that is, using a cast
operator or a method to force a conversion to occur—for all narrowing
conversions or conversions that might cause program termination (for
example, conversion of a String, such as "hello", to type Integer).
Option Strict and Data-Type
Conversions
Class Convert
◦ Class Convert’s methods explicitly convert data from one
primitive type to another.
◦ The name of each conversion method is the word To, typically
followed by the name of the type to which the method converts its
argument.
◦ For instance, to convert the String stored in
numberTextBox.Text to type Double, we use the statement
◦ Dim number As Double =
Convert.ToDouble(numberTextBox.Text)
◦ If numberTextBox does not contain a String that can be
converted to a Double value, a FormatExcepton will occur.
Classes and Methods
Experience has shown that the best way to develop and maintain a large
program is to construct it from small, simple pieces—a technique known
as divide and conquer.
Typical programs consist of one or more classes.
These classes are composed of smaller pieces called methods, instance
variables and properties.
You combine new classes with the prepackaged classes available in the
.NET Framework Class Library and in various other class libraries.
Classes and Methods
The .NET Framework Class Library provides a rich collection of classes
and methods for performing:
◦
◦
◦
◦
◦
◦
◦
◦
◦
◦
common mathematical calculations,
error checking,
building sophisticated GUI apps,
graphics,
string and character manipulations,
input/output operations,
XML processing,
database manipulations,
creating apps for the web
and many other useful operations.
Classes and Methods
You write methods to define specific tasks that a program may use one or
more times during its execution.
Although the same method can be executed from multiple points in a
program, the actual statements that define the method are written only
once.
A method is invoked (that is, made to perform its task) by a method call.
The method call specifies the method name and provides information (as
arguments) that the callee (that is, the method being called) requires to
do its job.
When the method completes its task, it returns control to the caller (that
is, the calling method).
Classes and Methods
There are several motivations for dividing code into methods.
◦ First, the divide-and-conquer approach makes program development more
manageable.
◦ A second motivation is software reusability—the ability to use existing
methods as building blocks for new programs.
◦ A third motivation is to avoid repeating code in a program—when code is
packaged as a method, the code can be executed from various points in a
program simply by calling the method. This also makes the code easier to
modify and debug.
Subroutines: Methods That Do Not
Return a Value
The programs presented earlier in the book each contain
at least one event-handler method that's called in response
to an event and performs the program’s tasks.
An event-handling method is a subroutine—a method that
performs a task but does not return a value.
A function is a method that performs a task then does
return a value to the calling method.
Subroutines: Methods That Do Not
Return a Value
Subroutine Declarations
◦ The format of a subroutine declaration is
◦ Sub method-name(parameter-list)
declarations and statements
End Sub
◦ Keyword Sub indicates that this method will perform a task but will
not return (that is, give back) any information to its calling method
when it completes its task.
Subroutines: Methods That Do Not
Return a Value
Parameters and the Parameter List
◦ The parentheses after the method name are used to indicate any
parameters—additional information that's required by the method to
perform its task.
◦ An empty set of parentheses indicates that a method does not require
any additional information and does not need any parameters.
◦ If there are parameters, they’re placed in a parameter-list—specified
by the set of parentheses following the method’s name.
Subroutines: Methods That Do Not
Return a Value
A method can specify multiple parameters by separating each from the
next with a comma—this is known as a comma-separated list.
Each parameter has a variable name and a type.
We refer to the part of the method that contains the keyword Sub, the
method name and the parameter list as the method header.
Functions: Methods That Return a
Value
A function is a method that returns a value to the caller.
Function Declarations
◦ The format of a function declaration is
◦ Function method-name(parameter-list) As return-type
declarations and statements
◦ End Function
◦ The method-name, parameter-list, and declarations and statements in a function declaration
behave like the corresponding elements in a subroutine declaration.
◦ In the function header, the return-type indicates the type of the value returned
from the function to its caller.
Passing Arguments: Pass-by-Value
vs. Pass-by-Reference
Arguments are passed in one of two ways—pass-by-value or pass-byreference.
When an argument is passed by value, the program makes a copy of the
argument’s value and passes the copy to the called method.
With pass-by-value, changes to the called method’s copy do not affect
the original variable’s value in the caller.
Scope of Declarations
Lifetime of a Variable
◦ Although a variable may not be in scope, it may still exist.
◦ A variable’s lifetime is the period during which the variable exists in memory.
◦ Some variables exist briefly, some are created and destroyed repeatedly, and
others are maintained through the program’s execution.
◦ Variables normally exist as long as the construct in which they are declared
exists—for instance, a local variable of a method will exist as the call to that
method is still executing.
Scope of Declarations
The basic scopes are:
◦ Block scope—The scope of a variable declared in a block is from
the point of the declaration to the end of the block
◦ Method scope—The scope of a method’s local-variable
declaration or parameter is from the point at which the declaration
appears to the end of that method.
◦ Class scope—The scope of a member that's declared in the class’s
body, but outside the bodies of the class’s methods is the entire
body of the class.
Method Overloading
Method overloading allows you to create methods with the same name
but different signatures—that is, there are different numbers and/or types
of parameters, or they’re listed in a different order (by type).
A method’s signature does not include its return type.
When you call an overloaded method, the compiler selects the proper
method by examining the number, types and order (by type) of the
arguments.
Optional Parameters
Methods can have optional parameters.
Declaring a parameter as Optional allows 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—that is, at the end of the parameter list.
Optional Parameters
When a parameter is declared as Optional, the caller has the option of
passing that particular argument.
For example, the method header
Function Power(ByVal base As Integer,
Optional ByVal exponent As Integer = 2) As Integer
specifies the last parameter exponent as Optional.
Any call to Power must pass at least an argument for the parameter
base, or a compilation error occurs.
Optionally, a second argument (for the exponent parameter) can be
passed to Power.
Optional Parameters
Consider the following calls to Power:
Power()
Power(10)
Power(10, 3)
The first call generates a syntax error because a minimum of one
argument is required for this method.
The second call is valid because one argument (10) is being passed—the
Optional exponent is not specified in the method call.
Download