.Net Programming

Swap using Call by Reference and Call By Value

Call by Reference makes the changes reflect back in the original variables while Call By Value works with copies of original values and changes are not reflected back in original values. Using the same concept, the SWAP function has been implemented in VB.Net.

Language : VB.Net

Call By Value, Call By Reference
[sourcecode language='vb']
Public Class Swap
Public a As Integer = 10
Public b As Integer = 20

Sub CallByValue(ByVal x As Integer, ByVal y As Integer)
Dim t As Integer
t = x
x = y
y = t
MsgBox(“Original Numbers : ” & “A=” & a & ” B=” & b)
MsgBox(“Swapped Numbers : ” & “X=” & x & ” Y=” & y)
End Sub

Sub CallByRef(ByRef x As Integer, ByRef y As Integer)
Dim t As Integer
t = x
x = y
y = t
MsgBox(“Original Numbers : ” & “A=” & a & ” B=” & b)
MsgBox(“Swapped Numbers : ” & “X=” & x & ” Y=” & y)
End Sub

Private Sub cmdByRef_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdByRef.Click
CallByRef(a, b)
End Sub

Private Sub cmdByVal_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdByVal.Click
CallByValue(a, b)
End Sub

End Class
[/sourcecode]



Leave a Comment

Notify me of followup comments via e-mail. You can also subscribe without commenting.


WordPress - Vaibhav Kanwal