ByVal vs. ByRef with Objects

Results 1 to 2 of 2

Thread: ByVal vs. ByRef with Objects

  1. #1
    Join Date
    Dec 1969

    Default ByVal vs. ByRef with Objects

    I am not clear on the differenct between ByVal parameters and ByRef parameters when the parameters are objects (i.e. arrays). If I use ByVal, then the object itself is modified. If I use ByRef, then the object itself is still modified. There seems to be no difference.<BR><BR>(I am comparing this to the way ByVal and ByRef works when passing variables like Integers)<BR><BR>Thanks in advance for the input!

  2. #2
    Join Date
    Dec 1969

    Default RE: ByVal vs. ByRef with Objects

    Here&#039;s my version of how it works.<BR><BR>ByVal is really only relevant to value data types.<BR><BR>Let&#039;s say you want to pass a reference data type ByVal to a Sub<BR><BR> Dim obj As New Foo<BR> obj.Bar = "Hello"<BR><BR> sub Blah (ByVal MyObj As Foo)<BR> myObj.Bar = "Goodbye"<BR> end sub<BR><BR>Now we pass the &#039;obj&#039; object to the Blah Sub...<BR><BR> Blah obj<BR><BR>If we, at this point, inspect the value of obj.Bar what value will it display?<BR><BR>Give up?<BR><BR>It will display the text "Goodbye"<BR><BR>This is because it is only the *reference* to the object that is being passed in to the Sub and not the actual object itself.<BR><BR>If you need to pass an object ByVal you will need to serialize it&#039;s data into a property bag (or something) and then use that data to instantiate a new instance inside the Sub. Something like this [psuedo-code]:<BR><BR> propBag = Serialize(obj)<BR><BR> Call Foo(propBag)<BR><BR>Then inside the Foo routine, you&#039;d do something akin to:<BR><BR> Sub Foo(...)<BR> <BR> Dim obj As New Foo = DeSerialize(propBag, Foo)<BR> obj.Bar = "Goodbye"<BR><BR> End Sub<BR><BR>I&#039;m sure that I haven&#039;t explained this very well, but, hopefully it gives you some insight into what is happening :)<BR> <BR>

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts