Re: String Init

From: Jon Skeet [C# MVP] (skeet_at_pobox.com)
Date: 02/09/04


Date: Mon, 9 Feb 2004 21:30:55 -0000


 <"Alvin Bruney [MVP]" <vapor at steaming post office>> wrote:
> Sometime ago, i posted a concern about initializing string variables to null
> v string.empty. I can't find the thread to reply to it so excuse this one.
>
> I just now thought of this. Isn't it dangerous to initialize variables to
> null in a garbage collected environment since garbage collection is
> non-dert...yada yada yada.
>
> Consider this, i have a routine spanning 200 lines of code. at the top of
> the routine i intialize an object to null. I intend to use this variable at
> line 160 for example. At line 10, a garbage collection occurs. Is my code at
> line 160 safe, the object is eligible for garbage collection because it has
> no roots?

What object? There *is* no object, because you've set the variable to
null. Don't forget: the value of a reference-type variable isn't an
object, it's a reference. A reference is either a way of identifying an
object, or null.

> This is theoretical and not apt to occur frequently but, right
> now, i'm thinking this is terrible if it can actually occur. (haven't given
> it much thought just yet)
>
> wouldn't it be best to intialize an object to a root like empty which would
> prevent this situation from occuring?

No - because then you're probably creating an object for no reason.
(Not in the case of String.Empty, but in other cases.)

-- 
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too


Relevant Pages

  • Re: String Init
    ... > No - because then you're probably creating an object for no reason. ... the object is eligible for garbage collection because it ... >> no roots? ... > object, it's a reference. ...
    (microsoft.public.dotnet.languages.csharp)
  • String Init
    ... i posted a concern about initializing string variables to null ... the routine i intialize an object to null. ... At line 10, a garbage collection occurs. ... no roots? ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: How to destroy arrays
    ... eligible for garbage collection in the Sub below? ... When a is an array reference, ... Actually, Scott didn't write that, fortunately - because it's not ... "roots" by the garbage collector until the end of the method. ...
    (microsoft.public.dotnet.general)
  • Re: How to free memory in Javascript?
    ... The only memory allocated here is the space allocated for i. ... How do i get rid of the reference to button? ... Whilst in some sense reference counting is a garbage collection pattern ...
    (microsoft.public.scripting.jscript)
  • Re: How to give selective access to the methods in a class?
    ... assigning null to a reference may transition an object from reachable to ... reference just for the sake of garbage collection. ... reachability in a more logical way. ...
    (comp.lang.java.programmer)