XML Node added by ref to a generic list?!
I have an XML node which I am adding to a generic list of xml nodes:
Code:
ListXml.Add(myXmlNode)
Now whenever I change the node afterwards, all members of the list turn into copies of the node. Why would the list keep track of this and more importantly how am I supposed to 'detach' my work node from that list?
Re: XML Node added by ref to a generic list?!
The short answer is that an XmlNode is a reference type, so you are really only adding the memory address of the object to your list. Change the data on that memory address and it will change in the list as well.
In order for us to help you, you need to show some more code. The fact that 'all members of the list' (did you mean all items in the list?) turn into copies is strange, it suggests that you are adding the same reference over and over instead of a new object every time, but without more code we can't tell.
Re: XML Node added by ref to a generic list?!
Hm, it's never easy. Yes I know I am using one work node to fill it with XML data and then adding it to a list over and over again. The problem is I need to access that data from different subs so the node is a vehicle for transferring XML code so to say.
I got it working with a global string previously but decided to use nodes to keep the number of conversions low. Now if I only were to figure out a way to create a node from another node BY VALUE the sun is going to shine again even though it's night and it's snowing :)
Re: XML Node added by ref to a generic list?!
So you're basically doing something like
Code:
Dim globalNode As XmlNode
Private Sub SomeMethod()
globalNode.Data = ...
someList.Add(globalNode)
End Sub
Private Sub OtherMethod()
globalNode.Data = something else
someList.Add(globalNode)
End Sub
Don't do that. It's the same object you keep accessing, and you are simply adding the same object to the list every time. When you change the Data property (that's just something I made up, I dunno what properties the XmlNode exactly has), it will change on that one instance only, and hence every item in the list (being the same item multiple times) reflects that change.
Instead of filling the same node with XML data over and over, assign a new instance of it first.
Code:
Private Sub SomeMethod()
globalNode = New XmlNode()
globalNode.Data = ...
someList.Add(globalNode)
End Sub
That should work, but it defeats the purpose of having the node globally. Actually, why do you need it globally at all?