Making a local copy of a Reference-type variable

Keith Howard

Active member
Joined
Jan 28, 2010
Messages
28
Programming Experience
5-10
Hello,

I am trying to do this, without the local copy just being a pointer to the original variable.

The original variable is the following received parameter:
ByVal Paragraph1 As Microsoft.Office.Interop.Word.Paragraph

I want to declare a local variable:
Dim Selection1 As Microsoft.Office.Interop.Word.Paragraph = Paragraph1.Application.Selection

The problem is that when I modify the variable Selection1, I seem to also be modifying the received parameter Paragraph1.
Therefore, is there a quick way to make a local copy of a Reference type variable?

Many thanks.

Keith
 
The whole point is that you wouldn't be making a copy of the variable. That's what you're already doing. What you want is to make a copy of the object that the variable is referring to.

The answer to your question is that it depends on the type. Some types have a Clone or Copy method whose purpose it is to make a shallow or deep copy of an object. In your case, I very much doubt that the type you're working with has such a method but you can check. Most likely you would have to create a new Paragraph object and then somehow populate it with the data you want. It depends how that type is implemented too. It's supposed to represent a paragraph so it may not be possible to work with one that isn't actually a paragraph in the document.
 
Hi there. Thanks for the response.
I think you grasped the exact issue I am trying to deal with. The solution sounds messy and, as you say, probably requires a different approach for different object types. This is a nice-to-have feature for me. My goal was to apply the coding standard "Never modify a received ByVal parameter; instead make a copy and modify that." I think we might change the standard. :) Thanks for your answer.
Kind regards,
Keith
 
Back
Top