Hi,
I'm new to C# and have run into a problem of my own making! I
originally took from the documentation that as long as I didn't use
the "ref" keyword in method declarations, that everything would be
passed "by value". I now believe I was incorrect and that it's only
types like int, bool, etc. that behave like that? i.e. things like
XmlDocument are always passed by reference in method calls?
I was writing a "wrapper" class around a PRIVATE XmlDocument but
because of the above lack of understanding, I don't think it's as
"encapsulated" as I thought it was!
e.g. in "MyWrapper" class:
-------------------------------------------------
....
private XmlDocument mvar_TheDocument = new XmlDocument(); //note
"private"
....
public MyWrapper()
{
mvar_TheDocument.Load("some path");
}
public XmlNode GetNodeByID(string sID)
{
return mvar_TheDocument.SelectSingleNode("/blah blah find the
node");
}
....
-------------------------------------------------
So, on some WebForm I now say:
....
MyClass objMyClass = new MyClass();
XmlNode objNode = objMyClass.GetNodeByID(sSomeID);
....
objNode.InnerXml = string.empty;
....
!!! Guess what? :-) The node in "mvar_TheDocument" gets cleared! Not
what I had in mind - I want MyClass to be the only place with code
that can update that XmlDocument.
The problem is worse because MyClass persists for a long time, over
many calls - so it's likely that I'm going to make a "coding mistake"
at some point and inadvertantly modify my core document.
What's the best thing to do (apart from sending me on a training
course!)? I assume I have to return a "copy" of the node somehow? How
does this impact memory management - does it get cleaned up once
nothing needs the "copy" any more or do I have to set "objCopy = null"
everywhere now?
Obviously, I've also misunderstood the "private" member concept - even
though the XmlDocument is "private", there's no runtime error when
"external" code indirectly modifies it like that? Wow! I'm way off
with this stuff!
Thanks for any help!