Function parameter gets changed

  • Thread starter Thread starter dferrell
  • Start date Start date
D

dferrell

For some reason myFunction in the below code is treating the parameter
oInputDoc1 as a ByRef rather than a ByVal. When the call returns, both
oInputDoc and oOutputDoc = "<root><name>Steve Jobs</name></root>"

When using a string instead of an xml document as the parameter the
argument and value remain ByVal and the results are as I would expect.




Private Sub Page_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
'Put user code to initialize the page here
Dim s As String = "<root><name>Bill Gates</name></root>"
Dim oInputDoc As System.Xml.XmlDocument = New
System.Xml.XmlDocument
Dim oOutputDoc As System.Xml.XmlDocument = New
System.Xml.XmlDocument
oInputDoc.LoadXml(s)
oOutputDoc = myFunction(oInputDoc)
Response.Write(oInputDoc.OuterXml)
Response.Write("<BR>")
Response.Write(oOutputDoc.OuterXml)
End Sub

Private Function myFunction(ByVal oInputDoc1 As System.Xml.XmlDocument)
As System.Xml.XmlDocument
Dim s As String = "<root><name>Steve Jobs</name></root>"
oInputDoc1.LoadXml(s)
Return oInputDoc1
End Function
 
Passing an object reference ByVal just protects the reference from changing,
not the state of the object. i.e., you're not passing the entire object,
just the object reference.
--
David Anton
www.tangiblesoftwaresolutions.com
Instant C#: VB.NET to C# Converter
Instant VB: C# to VB.NET Converter
Instant J#: VB.NET to J# Converter
Clear VB: Cleans up outdated VB.NET code
 
For some reason myFunction in the below code is treating the parameter
oInputDoc1 as a ByRef rather than a ByVal. When the call returns, both
oInputDoc and oOutputDoc = "<root><name>Steve Jobs</name></root>"

It is working just as it is supposed to. In your function, what gets
passed is a copy of the *reference* to the XmlDocument, not a copy of
the document itself. Thus, you have two different references to the
same object. So, inside your function, if you were to change the
*reference*, then the original reference would not be affected:

If you code were to do this:
Private Function myFunction(ByVal oInputDoc1 As System.Xml.XmlDocument)
As System.Xml.XmlDocument oInputDoc1 = New XmlDocument
End Function

Then your original document would not be affected.

When you pass a reference type ByVal, you get a copy of the reference.
When you pass a reference type ByRef, you pass the actual reference.

Either way, any changes you make to the properties,etc. will affect the
original object that each points to.
 
Back
Top