Method Parameter Types in VB.NET

In this article I will explain you about Method Parameter Types in VB.NET.
  • 7170

VB.NET supports parameter-passing styles to class member methods: ByVal, ByRef. All data types in VB.NET are passed by reference, but their default behavior is handled differently depending upon whether they are a value or reference type. You do not have to explicitly define it in your method. In fact, defining it explicitly causes a compile error. The ByVal parameter style indicates that the value type parameter being passed is not being altered upon returning from the method. Thus, the value of passed parameters of a value type, by default, cannot be changed.

For integral types and immutable classes such as strings, the VB.NET ByVal parameter type is similar to the C++ const type&. The ByVal type has no effect on mutable classes classes whose contents can be changed. The default behavior of references to mutable objects is handled as if the object was preceded with the ref keyword. In other words, with the ByVal keyword, you can pass the value's address to the method, but the value itself cannot be changed. To make the value changeable, use the VB.NET parameter type ByRef.

The VB.NET ByRef parameter type works like the type& standard reference in C++. A reference parameter does not create a new storage location. Instead, it represents the same storage location as the variable given as the argument in the function member invocation. Thus, the value of a reference parameter is always the same as the underlying variable.

A variable must be assigned before it can be passed as a reference parameter in a function member invocation. Within a function member, a reference parameter is considered initially assigned. Within an instance method or instance accessor of a structure type, the this keyword behaves exactly as a reference parameter of the structure type.

The out parameter is for explicitly referencing a parameter that will be filled by the called method. It has no complement in C++, but in COM+ the distinction was made in order to fulfill thorough marshalling back from a method. An out parameter differs from the ref parameter in that the caller doesn't need to initialize the variable prior to calling the method. Instead, a reference to the object can be sent uninitialized and initialized by the called method and then returned after instantiation. As with the ref parameter, an output parameter does not create a new storage location. Instead, it represents the same storage location as the variable given as the argument in the function member invocation. Thus, the value of an output parameter is always contained in the underlying variable that was passed into the method. Note that although an output parameter need not be assigned a value when it is passed into a method, it must be assigned a value when it returns from a method, otherwise the compiler will give an error.

Because structures are value types, when an instance of one is passed to a method, a copy is created of the structure. You can use the out keyword with a structure parameter to prevent the creation of large temporary storage space of a structure on the stack. VB.NET syntax encourages the return only of values or objects you really need and discourages the storage of temporary objects. This seems a sensible alternative to the C++ approach. In addition, the parameter distinction simplifies component programming for the developer.

I provides an example of how to use the ByBal, ByRef and out parameter modifiers.

Parameter Modifiers Example 1


// example method parameter usage; ByVal, ByRef
Imports System
 
Public Class ThirdFourthPower
    Public Sub XPower(ByVal intparam1 As Int32, ByRef intparam2 As Int32, ByVal intparam3 As Int32, ByVal intparam4 As Int32)
        intparam3 = intparam1 * intparam1 * intparam1
        intparam2 = intparam1 * intparam1 * intparam1 * intparam1
        ' ERROR: you cannot use out parameters as a value, right value here
        ' intparam2 = intparam3 * intparam1;
        intparam4 = intparam1 + intparam2 / intparam1
        ' notice operator
        ' precedence
    End Sub
End Class
 
Class MathyApp
    Public Shared Sub Main()
        Dim app1 As New ThirdFourthPower()
        Dim nTriple1 As Int32
        ' out parameters need not be initialized because filled in callee
        Dim nTriplePlus2 As Int32
        ' out
        Dim nQuadruple As Int32 = 0
        ' ref parameters must be initialized or assigned
        ' otherwise you receive ERROR : Use of unassigned local variable nQuadruple
        app1.XPower(3, nQuadruple, nTriple1, nTriplePlus2)
        Console.WriteLine("ByVal1: {0}", nTriple1.ToString())
        ' out parameter,
        ' 0
        Console.WriteLine("ByRef: {0}", nQuadruple.ToString())
        ' ref parameter,
        ' 81
        Console.WriteLine("ByVal2: {0}", nTriplePlus2.ToString())
        ' out parameter
        ' 0
        ' you should not use ref for returning values; use it if you really
        ' need in-place change
        ' note that in parameters are also references, but const, so you
        ' cannot change them.
        Console.ReadLine()
    End Sub
End Class

Screen Output Generated from above example

1.gif

Now presents a complete array example with ByVal and ByRef parameters.

Parameter Modifiers Example 2


// ByVal & ByRef - passing arrays

Imports System
Class MyApp
    ' out
    Public Shared Sub FillArray(ByVal myArray As Integer())
        ' Initialize the array:
        myArray = New Integer(5) {1, 2, 3, 4, 5, 6}
    End Sub 
    ' ref
    Public Shared Sub FillArray2(ByRef arr As Integer())
        ' Create the array on demand:
        If arr Is Nothing Then
            arr = New Integer(10) {}
        End If
        ' Otherwise fill the array:
        arr(0) = 19
        arr(4) = 1919
    End Sub 
    ' implicit ref default for references, not in
    Public Shared Sub WriteArray(ByVal myArray As Integer())
        ' myArray[2] = 19; // CAVEAT: this is also valid
        Console.WriteLine("Array elements are:")
        Dim i As Integer = 0
        While i < myArray.Length
            Console.WriteLine(myArray(i))
            System.Math.Max(System.Threading.Interlocked.Increment(i), i - 1)
        End While
    End Sub
    Public Shared Sub Main()
        ' Initialize the array:
        Dim myArray2 As Integer() = {1, 2, 3, 4, 5}
        FillArray2(myArray2)
        WriteArray(myArray2)
        Console.ReadLine()
    End Sub
End Class

Screen Output Generated from above example

2.gif

Parameter Modifiers Example 3

Imports System 
Public Class SomeItems
    Public One As Integer
    Public Two As String
End Class
Public Class App
    Public m_three As Integer = 5
    Public Function methodTwo(ByVal o As SomeItems, ByVal s As String) As Integer
        o.One = m_three
        s = "BlaBla"
        Return 0
    End Function 
    Public Function methodTwo2(ByVal o As SomeItems) As Integer
        o.One = m_three
        o.Two = "Is Gone"
        Return 0
    End Function 
    Public Shared Sub Main(ByVal args As String())
        Dim _a As New App()
        Dim si As New SomeItems()
        si.One = 1
        si.Two = "Goodbye string"
        Console.WriteLine("Before = {0} - {1}", si.One, si.Two)
        _a.methodTwo(si, si.Two)
        Console.WriteLine("After = {0} - {1}", si.One, si.Two)
        _a.methodTwo2(si)
        Console.WriteLine("After = {0} - {1}", si.One, si.Two)
        Console.ReadLine()
        Return
    End Sub
End Class

Screen Output Generated from above example

3.gif

Conclusion


Hope this article would have helped you in understanding Method Parameter Types in C#. See other articles on the website on .NET and C#.

Categories

More Articles

© 2020 DotNetHeaven. All rights reserved.