473,587 Members | 2,510 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Value/Reference Types - Oooooops!

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
"encapsulat ed" as I thought it was!

e.g. in "MyWrapper" class:

-------------------------------------------------
....
private XmlDocument mvar_TheDocumen t = new XmlDocument(); //note
"private"
....
public MyWrapper()
{
mvar_TheDocumen t.Load("some path");
}

public XmlNode GetNodeByID(str ing sID)
{
return mvar_TheDocumen t.SelectSingleN ode("/blah blah find the
node");
}
....
-------------------------------------------------
So, on some WebForm I now say:

....
MyClass objMyClass = new MyClass();
XmlNode objNode = objMyClass.GetN odeByID(sSomeID );
....
objNode.InnerXm l = string.empty;
....

!!! Guess what? :-) The node in "mvar_TheDocume nt" 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!
Nov 12 '05 #1
5 2939
When you pass (by value) a reference to an object, the called method gets
exactly that: a copy of the reference to the object. Since it was passed by
value, the called method can't modify the original reference (the one in the
calling method's scope), but it can change the state of the object that the
argument refers to, providing the object has any public members that can
change its state.

If, on the other hand, you pass a reference BY REFERENCE, the called method
is looking directly at the calling method's variable, and could change it.
So when the method returns, the calling method might find that the variable
now points to a different object.

Clear as mud?
Tom Dacon
Dacon Software Consulting

"Jerry Morton" <Je************ @mail.com> wrote in message
news:11******** *************** ***@posting.goo gle.com...
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
"encapsulat ed" as I thought it was!

e.g. in "MyWrapper" class:

-------------------------------------------------
...
private XmlDocument mvar_TheDocumen t = new XmlDocument(); //note
"private"
...
public MyWrapper()
{
mvar_TheDocumen t.Load("some path");
}

public XmlNode GetNodeByID(str ing sID)
{
return mvar_TheDocumen t.SelectSingleN ode("/blah blah find the
node");
}
...
-------------------------------------------------
So, on some WebForm I now say:

...
MyClass objMyClass = new MyClass();
XmlNode objNode = objMyClass.GetN odeByID(sSomeID );
...
objNode.InnerXm l = string.empty;
...

!!! Guess what? :-) The node in "mvar_TheDocume nt" 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!

Nov 12 '05 #2
Tom - I read your reply (twice :-) and I do now understand. It's
certainly an interesting nuance.

I found that if I return a "copy" of my data I can avoid the problem,
however I still have a problem with "XmlNode":

e.g.

-------------------------------------------------
....
private XmlDocument mvar_TheDocumen t = new XmlDocument(); //note
"private"
....
public MyWrapper()
{
mvar_TheDocumen t.Load("some path");
}
public XmlDocument GetDocument()
{
//The following returns a "copy" of the document - the "private
mvar_TheDocumen t" remains untouchable outside this object.
XmlDocument objNewDoc = new XmlDocument();
objNewDoc.LoadX ml(mvar_TheDocu ment.OuterXml);
return objNewDoc;
}

public XmlNode GetNodeByID(str ing sID)
{
//How do I return a "copy" of an XmlNode - The following line gets a
compiler error: "Cannot create an instance of the abstract class or
interface 'System.Xml.Xml Node'"
XmlNode objNewNode = new XmlNode();
...
}
....
-------------------------------------------------

How do I do this for "XmlNode". Is this "copy" method even the right
way to do all this?

Although I understand HOW it happens, I'm still not clear WHY .NET
allows a "private" member variable to be accessed this way. Seems
inconsistent?

Thanks.

"Tom Dacon" <td****@communi ty.nospam> wrote in message news:<#X******* *******@TK2MSFT NGP12.phx.gbl>. ..
When you pass (by value) a reference to an object, the called method gets
exactly that: a copy of the reference to the object. Since it was passed by
value, the called method can't modify the original reference (the one in the
calling method's scope), but it can change the state of the object that the
argument refers to, providing the object has any public members that can
change its state.

If, on the other hand, you pass a reference BY REFERENCE, the called method
is looking directly at the calling method's variable, and could change it.
So when the method returns, the calling method might find that the variable
now points to a different object.

Clear as mud?
Tom Dacon
Dacon Software Consulting

Nov 12 '05 #3


Jerry Morton wrote:

public XmlNode GetNodeByID(str ing sID)
{
//How do I return a "copy" of an XmlNode - The following line gets a
compiler error: "Cannot create an instance of the abstract class or
interface 'System.Xml.Xml Node'"
XmlNode objNewNode = new XmlNode();


You can clone nodes in the DOM e.g.
node.CloneNode( true)
to create a clone. However that cloned node still belongs to the same
ownerDocument as node so I can currently not assess whether that is of
any help to you.
Maybe you can explain in more detail how you want to consume the node
returned by that method.

--

Martin Honnen
http://JavaScript.FAQTs.com/
Nov 12 '05 #4
Hi Martin,
I would prefer that the node returned from my function had no
relationship to the private XmlDocument. Can XmlNodes even exist in
isolation like this? i.e. without a parent XmlDocument? I appreciate
that a CLONED node may not cause the same problems (like setting
objNode.InnerXm l=string.empty! ) however this "cloning" does sound like
a "memory leak waiting to happen"? This object persists for a long
time too...

The purpose of all this is to completely encapsulate a PRIVATE
XmlDocument so that it can't be modified by code outside the class. I
can't be the first person who want to do this :-)

I still can't believe that a private member variable behaves this way.
However, if it does then I can live with making "copies" of the
document to pass back from functions. But does this mean that when I
only want to pass one node of the document, I actually have to pass
back an XmlDocument containing only that node?

Martin Honnen <ma*******@yaho o.de> wrote in message news:<eO******* *******@TK2MSFT NGP10.phx.gbl>. ..
Jerry Morton wrote:

public XmlNode GetNodeByID(str ing sID)
{
//How do I return a "copy" of an XmlNode - The following line gets a
compiler error: "Cannot create an instance of the abstract class or
interface 'System.Xml.Xml Node'"
XmlNode objNewNode = new XmlNode();


You can clone nodes in the DOM e.g.
node.CloneNode( true)
to create a clone. However that cloned node still belongs to the same
ownerDocument as node so I can currently not assess whether that is of
any help to you.
Maybe you can explain in more detail how you want to consume the node
returned by that method.

Nov 12 '05 #5


Jerry Morton wrote:

I would prefer that the node returned from my function had no
relationship to the private XmlDocument. Can XmlNodes even exist in
isolation like this? i.e. without a parent XmlDocument? I appreciate
that a CLONED node may not cause the same problems (like setting
objNode.InnerXm l=string.empty! ) however this "cloning" does sound like
a "memory leak waiting to happen"? This object persists for a long
time too...
Inside the DOM object model implemented in .NET a node always belongs to
its owner document, modelled in the
node.OwnerDocum ent
property. Thus even if you clone nodes with
node.CloneNode( )
you still have nodes associated with the owner document (and linked to
it via node.OwnerDocum ent).
As for the memory leak, managed code in .NET has garbage collection so
once variables referencing nodes go out of scope they are available for
garbage collection. I am not sure what else you could do (or even expect
to happen behind the scenes) than cloning nodes.
The purpose of all this is to completely encapsulate a PRIVATE
XmlDocument so that it can't be modified by code outside the class. I
can't be the first person who want to do this :-)

I still can't believe that a private member variable behaves this way.
However, if it does then I can live with making "copies" of the
document to pass back from functions. But does this mean that when I
only want to pass one node of the document, I actually have to pass
back an XmlDocument containing only that node?


As said, you can use CloneNode to create a clone of your node but that
clone is still linked to the original document via the OwnerDocument
property. And of course while the original node might sit somewhere in
the document tree (have a ParentNode) the cloned node doesn't have a
ParentNode.

--

Martin Honnen
http://JavaScript.FAQTs.com/
Nov 12 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
1547
by: Javier Campos | last post by:
WARNING: This is an HTML post, for the sake of readability, if your client can see HTML posts, do it, it doesn't contain any script or virus :-) I can reformat a non-HTML post if you want me to (and if this doesn't see correctly with non-HTML viewers) Ok, I'm fed up with this so I'll explain the situation here and my approach (which sucks),...
1
1815
by: Rafael Veronezi | last post by:
Just to fix, correct me if I am wrong... With reference types (objects), if I assign an object to another, the assignment will be the address of the object, and not a copy of it's contents right? With value types (structs), if I assign an object to another, I'll be copying it's data to the left side of the assignment, and not it's address. ...
19
2136
by: daniel | last post by:
This is a pretty basic-level question, but I'd really like to know, so thanks for any help or pointers you can provide (like what I would google for ;o) Suppose: <code> myFunc() {
24
2598
by: ALI-R | last post by:
Hi All, First of all I think this is gonna be one of those threads :-) since I have bunch of questions which make this very controversial:-0) Ok,Let's see: I was reading an article that When you pass a Value-Type to method call ,Boxing and Unboxing would happen,Consider the following snippet: int a=1355; myMethod(a); ......
5
2089
by: Zach | last post by:
When it is being said that, "value types are created on the stack or inline as part of an object". If a value type is created in an object, and that object is being called, the value type in that object, is still created on the stack, I would say, so I don't understand this inline business. Apart from the fact that it is my understanding...
4
2282
by: Jon Slaughter | last post by:
I'm reading a book on C# and it says there are 4 ways of passing types: 1. Pass value type by value 2. Pass value type by reference 3. Pass reference by value 4. Pass reference by reference. My interpretation: 1. Essentially pushes the value type on the stack
11
2365
by: garyusenet | last post by:
I have 'cli via c# on order', and in the mean time am reading 'Pro C# 2005 and the .NET platform' (Andrew Troelson). I'm just reading about the 'five types defined in the CTS'. Specifically Struct. Now Troelson described the struct type as 'a lightweight class type having value based semantics'. Looking at his example I cant see any...
45
18834
by: Zytan | last post by:
This returns the following error: "Cannot modify the return value of 'System.Collections.Generic.List<MyStruct>.this' because it is not a variable" and I have no idea why! Do lists return copies of their elements? Why can't I change the element itself? class Program { private struct MyStruct
10
13637
by: Robert Dailey | last post by:
Hi, I noticed in Python all function parameters seem to be passed by reference. This means that when I modify the value of a variable of a function, the value of the variable externally from the function is also modified. Sometimes I wish to work with "copies", in that when I pass in an integer variable into a function, I want the...
0
7852
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8216
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8349
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
6629
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
5395
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3845
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3882
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2364
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1455
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.