Argument Passing ByValue and ByReference


In this post I will explain about Passing the Argument by value and by Reference in VB.NET

Lets Start…….

In .Net every argument that a method takes is preceded by two ways either By Val or By Ref.

Arguments passing By Val : It describes passing the arguments by value, that means the called procedure cannot modify the variable itself.

Arguments passing By Ref: It describes passing arguments by reference, which means the procedure can modify the variable itself.

Passing arguments ByVal or ByRef in Value Types:

If we pass the argument to the method by Val, the duplicate copy of that variable is created on the stack (simply local copy of that variable is created). Because of this any changes we make to that argument will not persist beyond that method.

For Example:

Public Class Demo

Public sub Foo(ByVal x as Integer)

X= 3

End Sub

End Class

Now if we call this method passing some value for x, then the value for x is newly assigned value it will not 5

Public shared sub Main()

Dim X as Integer = 5

//Call the Foo method passing value as argument


End Sub

End Class

Output :

X: 3

How is this happening?

Let us have a clear look……..                                     In Stack

In Main before Foo is called                                        X = 5    (Initializing X)

In Foo the value of x is                                                X = 3    (Assign new value to X as 3)

In Main after Foo is returned                                       X = 3

So, if you want the original variable to be changed?Then you can use By Ref

We understand that every variable in .net is located (save) somewhere in our computer memory.

For example: from the above code the value for variable ‘X’ to be stored at memory location 12356(something), so framework simply tells the system that to look up the value at that memory location(12356) and it will take the value at that location as ‘3’

When we pass the argument by reference, framework actually passes this memory location to the method.

Public sub Foo1(ByRef X as Integer)


End Sub

Now if we call this method,

Public shared sub Main()

DimX as Integer =3

//Call the Foo method passing value as argument


End Sub

End Class

So, the method will set the value of that memory location to 3, and the value of the variable ‘X’ is actually changed to 3 this time! The message box will thus show “3”. Because we pass the argument as By Ref.

In main before foo is called                        X=3

In foo                                                             X=5

In Heap memory                                           X=3

Memory location: (12378)

I hope it was clear and easy…………..