Raymond Lewallen

A few things .Net, a few things Sql

<November 2008>
SuMoTuWeThFrSa
2627282930311
2345678
9101112131415
16171819202122
23242526272829
30123456


Navigation

General

Subscriptions

Post Categories



Monday, December 06, 2004 - Posts

ByVal and ByRef for beginners
I like to provide help to the beginning programmers, and understanding the difference in ByVal and ByRef is something I see many of them ignore. So here's a tidbit of information, again, for the beginners out there.

You need to understand and grasp this simple concept of value types being passed ByVal and ByRef. Soon, we'll talk about what happens when passing reference types ByVal and ByRef. This will also lead us into discussions about boxing and unboxing. For now, lets just concentrate on value types. When you pass an object by value, a copy is made of that object's state in memory and allocated to another memory space, so you have two copies of the object. Look at the following example in VB:

Class Foo

Public x As Int32

Public Sub New()
x = 5
Main(x)
End Sub

Private Sub Main(ByVal y As Int32)
y = 6
Console.WriteLine(x)
Console.WriteLine(y)
End Sub

End Class

Now in this example, the output will be the following:
5
6

This is because when we passed x to Main by value, we made a copy of the state of x in memory and that copy is used in Main. When Main is finished executing, the copy made for y goes away and we no longer have access to it.

Now look at this code:

Class Foo

Public x As Int32

Public Sub New()
x = 5
Main(x)
End Sub

Private Sub Main(ByRef y As Int32)
y = 6
Console.WriteLine(x)
Console.WriteLine(y)
End Sub

End Class

The output for this code is:
6
6

The reason x is 6 and not 5 is because we actually passed to Main a pointer that tells Main where in memory it can find x; passing by reference. No copy is made and anything done to y also changes the state of x, because y is only a reference to where x is located in memory, not a new copy of the state of x. For this reason, you will never write code such as the following (which I found in some friends code and is what lead to this topic)
Class Foo

Public x As Int32

Public Sub New()
x = 5
x = Main(x)
End Sub

Private Function Main(ByRef y As Int32) As Int32
y = 6
Return y
End Sub

End Class
There is no need to return the value of y, because you were given y as a pointer to x. When you change y, you are changing x, as discussed above.

Now, the concept of ByVal and ByRef goes much, much deeper, but we'll save that for a later time.

posted Monday, December 06, 2004 6:19 AM by rlewallen




Powered by Dot Net Junkies, by Telligent Systems