Chapter 1: Lesson 4: Using Methods
Methods do the work of classes and structures.
Methods represent actions your class can take.
There are generally 2 varieties of Methods (in VB)
- those that return a value (functions)
- those that do not return a value (subs)
C# makes no distinction between the two.
A method is executed when it is called.
The Main method is a special case. It is called upon initiation of program execution. Destructors, another special case, are called by the runtime just prior to destruction of an object. Constructors, a third special case, are executed by an object during its initialization.
Method Variables are destroyed as soon as the Method has finished executing. (They have Method Scope)
Variables within smaller divisions of methods have even more limited scope. E.g.) a Loop within a method
Visual Basic allows you to create method variables that are not destroyed after a method finishes execution. - Static method variables
They persist in memory and retain their values through multiple executions of a method.
These are declared using the static keyword.
Methods can have Parameters.
Parameters are values required by the method.
Parameters of a method can be passed in 2 ways: By Value or By Reference.
In .NET By Value is the default.
By value means that whenever a parameter is supplied, a copy of the data contained in the variable is made and passed to the method. Any changes made in the value passed to the method are not reflected in the original variable.
When parameters are passed by reference,
A reference to the memory location where the variable resides is supplied instead of an actual value. Thus, every time the method performs a manipulation on that variable, the changes are reflected in the actual object.
In Visual Basic .NET, you are able to specify optional parameters for your methods.
Optional parameters must be last in a method declaration and you must supply default values for them.
A constructor is the first method that is run when an instance of a type is created.
In VB it is always Sub New. You use a constructor to initialize class and structure data before use.
Constructors can never return a value and can be overridden to provide custom initialization functionality. Eg) Visual Basic .NET
Public Class aClass
Public Sub New()
' Class initialization code goes here
End Sub
End Class
A destructor is the last method run by a class. A destructor (known as a Finalizer in Visual Basic) contains code to “clean up” when a class is destroyed.
Public Class aClass
Protected Overrides Sub Finalize()
' Clean up code goes here
End Sub
End Class
NOTE
In Visual Basic, the Finalizer is always Sub Finalize ()
must use the Overrides keyword. (see example above)
Because garbage collection does not occur in any specific order, it is impossible to determine when a class’s destructor will be called.