Search code examples
c#referencegarbage-collectionusingidisposable

Does using statement keep a reference to object(s) it receive?


When using "using" statement like this:

  using (Global.Instance.BusyLifeTrackerStack.GetNewLifeTracker())
  {
    ...

instead of

  using (var lt = Global.Instance.BusyLifeTrackerStack.GetNewLifeTracker())
  {
    ...

Does "using" statement will keep a reference to the returned object in order to ensure it will not be garbage collected too much earlier?... either if there is no explicit variable declared for it (first sample code)?

Second sample code is clearly fine, but first one???

Any documentation and/or reference to the information would be appreciated.


Solution

  • To answer the documentation and reference portion of your question:

    The documentation for the using statement notes:

    The using statement calls the Dispose method on the object in the correct way, and (when you use it as shown earlier) it also causes the object itself to go out of scope as soon as Dispose is called. Within the using block, the object is read-only and cannot be modified or reassigned.

    As far as the syntax of the first code block goes, the C# standard has the following for the syntax:

    using_statement
        : 'using' '(' resource_acquisition ')' embedded_statement
        ;
    
    resource_acquisition
        : local_variable_declaration
        | expression
        ;
    

    There, you'll note that resource_acquisition can be a local variable declaration, or an expression, which is what your first code block uses.