"using" vs "= null" and object lifetime

Tech-Archive recommends: Fix windows errors by optimizing your registry

From: MuZZy (leyandrew_at_yahoo.com)
Date: 02/17/05


Date: Thu, 17 Feb 2005 10:02:52 -0500

Hi,

Lately i've been (and still am) fixing some memory leaks problems in the project i just took over
when i got this new job. Among the other issues i've noticed that for localy created objects it
makes difference to explicitly put them to null after working with them is done - it somehow makes
the GC collect them sooner, like here:

void SomeFunc()
{
        MyClass c = new MyClass();
        c.CallSomeOtherFunc();
        c = null;
}

If i don't put "c" to null time to get it collected is way longer than if i explicitly dereference
the object. It's really strange, as it's obvoius that object's lifetime is limited by body of
"SomeFunc". But anyway, my question is: is there any difference in the first example compared to this:

void SomeFunc()
{
        using (MyClass c = new MyClass())
        {
                c.CallSomeOtherFunc();
        }
}

The second way looks nicer for me and avoids forgetting to explicitly dereference the object,
but i'm not sure if this second case is being treated the same way as the first one.

Any suggestions/ideas would be highly appreciated!

Thnak you,
Andrey



Relevant Pages

  • Re: "using" vs "= null" and object lifetime
    ... >>Lately i've been fixing some memory leaks problems in ... >>than if i explicitly dereference the object. ... I haven't tested that in Release mode - just Debug. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: "using" vs "= null" and object lifetime
    ... MuZZy wrote: ... > Lately i've been fixing some memory leaks problems in ... > than if i explicitly dereference the object. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: "using" vs "= null" and object lifetime
    ... >>Lately i've been fixing some memory leaks problems in the project i just took over ... >>void SomeFunc() ... So if i'm more concerned about shorter object lifetime, ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: "using" vs "= null" and object lifetime
    ... > void SomeFunc() ... > The second way looks nicer for me and avoids forgetting to explicitly dereference the object, ...
    (microsoft.public.dotnet.languages.csharp)