More about Methods

Team-Fly    

 
Application Development Using Visual Basic and .NET
By Robert J. Oberg, Peter Thorsteinson, Dana L. Wyatt
Table of Contents
Chapter 4.  VB.NET Essentials, Part II


More about Methods

In this section we look at several other topics pertaining to methods in VB.NET:

  • Parameter passing

  • Variable-length parameter lists

  • Method overloading

  • Optional parameters

Parameter Passing

Programming languages have different mechanisms for passing parameters. One mechanism is known as call- by-value . This means that the actual data values are copied and passed to the method being called. These copied values are pushed onto the stack, and the called function obtains independent copies of the values. Any changes made to these values will not be propagated back to the calling program. VB.NET supports this mechanism of parameter passing using the ByVal keyword, but VB.NET also supports call-by-reference parameters.

Some terminology will help us in the following discussion. Storage is allocated on the stack for method parameters. This storage area is known as the activation record . It is popped off when the method is no longer active. The actual parameters of a method are the parameters as seen within the method call (i.e., in the method client code). The formal parameters of a method are the expressions between commas in the parameter list of the called method.

Value Parameters

Parameter passing is the process of initializing the storage of the formal parameters by the actual parameters. Passing parameters with the ByVal keyword is known as call-by-value , in which the values of the actual parameters are copied into the storage of the formal parameters. Call-by-value is "safe," because the method never directly accesses the actual parameters, only its own local copies. But there are drawbacks to call-by-value:

  • There is no direct way to modify the value of an argument. You may use the return type of the method, but that allows you to pass only one value back to the calling program.

  • There is overhead in copying a large object.

The overhead in copying a large object is borne when you pass a struct instance. If you pass a class instance, or an instance of any other reference type, you are passing only a reference and not the actual data itself. This may sound like call-by-reference, but what you are actually doing is passing a reference by value.

The ValueMath example shows how to pass parameters to a method using call-by-value.

 graphics/codeexample.gif ' Function call with actual parameters sum = ValueMath.Add(5, 7) ... ' Function implementation with formal parameters Public Shared Function Add(_  ByVal  x As Integer, _  ByVal  y As Integer) _    As Integer    Return x + y End Function ... 

Reference Parameters

Consider a situation in which you want to pass more than one value back to the calling program. VB.NET provides a clean solution through reference parameters . You declare a reference parameter with the ByRef keyword, which is placed before the formal parameter. A reference parameter does not result in any copying of a value. Instead, the formal parameter and the actual parameter refer to the same storage location. Thus, changing the formal parameter will result in the actual parameter changing, as both are referring to exactly the same storage location.

The program ReferenceMath illustrates using ByRef parameters. There is a single method, Calculate , which passes back two values as reference parameters.

 graphics/codeexample.gif ' ReferenceMath.vb Public Class ReferenceMath    Public Shared Sub Calculate(_     ByVal x As Integer, _     ByVal y As Integer, _  ByRef  sum As Integer, _  ByRef  prod As Integer)       sum = x + y       prod = x * y    End Sub End Class 

Notice the use of the ByRef keyword in front of the third and fourth formal parameters. Here is the corresponding test program:

 ' TestReferenceMath.vb Public Module TestReferenceMath    Public Sub Main()  Dim sum As Integer = 0, product As Integer = 0  ReferenceMath.Calculate(5, 7,  sum  ,  product  )       Console.WriteLine("sum = {0}", sum)       Console.WriteLine("product = {0}", product)    End Sub End Module 

We use the ByRef keyword only on the formal parameters, not on the actual parameters.

Method Overloading

In most traditional programming languages, you need to create unique names for all your methods. If methods do basically the same thing but apply only to different data types, it becomes tedious to create artificially unique names . For example, suppose you have a FindMax method that can find the maximum of two Integer or two Long or two String parameters. If we need to come up with a unique name for each method, we would have to create method names such as FindMaxInteger , FindMaxLong , and FindMaxString .

In VB.NET, as in other object-oriented languages such as C#, C++, and Java, you may overload method names. That is, different methods can have different names if they have different signatures . Two methods have the same signature if they have the same number of parameters, the parameters have the same data types, and the parameters are in the same order. The return type does not contribute to defining the signature of a method.

At runtime the compiler will resolve a given invocation of the method by trying to match up the actual parameters with formal parameters. A match occurs if the parameters match exactly or if they can match through an implicit conversion. For the exact matching rules, consult the VB.NET Language Specification .

The program OverloadDemo example illustrates method overloading. The method FindMax is overloaded to take either Long or String parameters. The method is invoked three times, for Integer , Long , and String parameters. There is an exact match for the case of Long and String . The call with Integer actual parameters can resolve to the Long version, because there is an implicit conversion of Integer into Long .

 graphics/codeexample.gif ' OverloadDemo.vb Imports System Public Module OverloadDemo    Public Sub Main()       Dim x1 As Integer = 5, x2 = 7       Dim y1 As Long = 5000000000L, y2 = 7000000000L       Dim s1 As String = "fifteen", s2 As String = "seven"       Console.WriteLine("max of {0}, {1} = {2}", _          x1, x2, FindMax(x1, x2))       Console.WriteLine("max of {0}, {1} = {2}", _          y1, y2, FindMax(y1, y2))       Console.WriteLine("max of {0}, {1} = {2}", _          s1, s2, FindMax(s1, s2))    End Sub    Function FindMax(ByVal a As Long, ByVal b As Long) _     As Long       If a < b Then          Return b       Else          Return a       End If    End Function    Function FindMax(ByRef a As String, ByRef b As String) _     As String       If String.Compare(a, b) <= 0 Then          Return b       Else          Return a       End If    End Function End Module 

Variable-Length Parameter Lists

Our FindMax methods in the OverloadDemo example are very specific with respect to the number of parametersthere are always exactly two parameters. Sometimes you may want to be able to work with a variable number of parametersfor example, to find the maximum of two, three, four, or more numbers . VB.NET provides the ParamArray keyword, which you can use to indicate that an array of parameters is provided. Sometimes you may want to provide both a general version of your method that takes a variable number of parameters and also one or more special versions that take an exact number of parameters. The special version will be called in preference, if there is an exact match. The special versions are more efficient. The program VariableMax illustrates a general FindMax method that takes a variable number of parameters. There is also a special version that takes two parameters. Each method prints out a line identifying itself, so you can see which method takes precedence. Here is the program:

 graphics/codeexample.gif ' VariableMax.vb Imports System Public Module VariableMax    Public Sub Main()       Console.WriteLine(_          "max of {0}, {1} = {2}", _          5, 7, FindMax(5, 7))       Console.WriteLine(_          "max of {0}, {1}, {2} = {3}", _             500, 5, 7, FindMax(500, 5, 7))       Console.WriteLine(_          "max of {0}, {1}, {2}, {3} = {4}", _          500, 5, 7, 80, FindMax(500, 5, 7, 80))    End Sub  Function FindMax(_   ByVal a As Integer, _   ByVal b As Integer) As Integer  Console.WriteLine("FindMax with Two Parameters")       If a < b Then          Return b       Else          Return a       End If    End Function  Function FindMax(_   ByVal ParamArray args() As Integer) As Integer  Console.WriteLine(_          "FindMax with Variable Number of Parameters")       Dim imax As Integer = Int32.MinValue       Dim i As Integer       For i = 0 To args.Length - 1          If args(i) > imax Then             imax = args(i)          End If       Next       Return imax    End Function End Module 

Here is the output:

 FindMax with Two Parameters max of 5, 7 = 7 FindMax with Variable Number of Parameters max of 500, 5, 7 = 500 FindMax with Variable Number of Parameters max of 500, 5, 7, 80 = 500 

Team-Fly    
Top
 


Application Development Using Visual BasicR and .NET
Application Development Using Visual BasicR and .NET
ISBN: N/A
EAN: N/A
Year: 2002
Pages: 190

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net