Parameter passing / referencing in .Net

Posted Mon, Jul 17 2006 11:16 PM by Mischa Kroon
When looking at the following code:
StringBuilder first = new StringBuilder();
StringBuilder second = first;
first.Append ("hello");
first = null;
Console.WriteLine (second);

What would you think the output would be ?
If it is anything other then: hello

You will want to look at the following tutorial:
Parameter passing in C#

 

 

Filed under: , ,

Comments

# re: Parameter passing / referencing in .Net

Tuesday, July 18, 2006 1:32 AM by Ramon Smits

I would think that it would be "hello" but your post makes me doubt this :-)

# re: Parameter passing / referencing in .Net

Saturday, July 22, 2006 9:37 AM by silencer

@woldesa, when you set first to null, you just set the reference to null, not the value. so the origin stringbuilder still exists because it's still referenced from second. the content of the stringbuilder referenced by second is of course still "hello" in the last line of this code.

# re: Parameter passing / referencing in .Net

Sunday, July 23, 2006 11:12 PM by Dennis van der Stelt

Silencer is right. Values of reference types are stored in the managed heap. It wil exist until the garbage collector passes starts and is notified about the "object value" if it has no ROOT object(s). In other words, if it's no longer used by your (or any other) application. Only than the object is really "deleted" from memory. It's a little bit more complicated than this, but it's a fair explanation I think.

When 'second' still has a reference to the stringbuilder object, it's not deleted. Remember that your reference objects aren't deleted until the garbage collector is started. And you can't tell when it's started up, because this is determined by the GC itself. Or you start it yourself with gc.collect() or shut down your app (which makes it start immediatly).

Leave a Comment

(required) 
(required) 
(optional)
(required) 
Please add 1 and 5 and type the answer here: