Banner Ad

Monday, October 7, 2013

VB.Net ByRef Variable : A Small Warning

By Francis   Posted at   12:44 PM   VB.Net No comments
In VB.Net, programmers often used the variable by reference using the keyword ByRef. Normally, reference variables not copied like Value type variables. There are some scenarios arise to use or pass a variable as reference to another function/subroutine and change them within the function/subroutine.

For, example consider the below code:


Partial Class _Default
    Inherits System.Web.UI.Page
    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim strLen As String = String.Empty
        ' Store a decimal in a string
        strLen = 10.56
        ' Call the function
        ' Note here typcast the STRING to DECIMAL
        Convert(CDec(strLen))
        ' Print the value 
        lblResult.Text = strLen
    End Sub
    Private Sub Convert(ByRef decLen As Decimal)
        ' Alter the REFERENCE variable here
        decLen = 11.56
    End Sub
End Class

The function “Convert” accepts the a decimal type Reference variable and altered it.

Take a close look at how the function “Convert” called. We pass the typecast the “String” variable to “Decimal” and pass it to the function. So after call the function we expect the result “11.56” stored in the variable “strLen”. But it won’t work like that it should contains “10.56” after the subroutine call also.
          In the above code snippet, we made a mistake. That is in line 9, we use the “CDec” function to convert the string into Decimal, which actually takes a copy of the respective variable and sent to it to the “Convert” Function. That’s why even though we set the function’s argument as byref, we are not get the correct result.

Instead of the line 9, if we use the below line of code we can get the correct result:
        
Dim decLen As Decimal = CDec(strLen)
Convert(decLen)

In the above code, we just create a new decimal variable, and hold the typcast value of "strLen" into it. It will then passed to the "Convert" subroutine. Finally we got the result "11.56".

Hope this helps a bit!

About Francis

Francis, an Associate at Cognizant. Having 7+ Years of experience in Microsoft web technologies.

0 comments :

Please give your valuable comments to improve the contents

Connect with Us