locked
How using works? RRS feed

  • Question

  • Example:

    Graphics g = Graphics.FromImage(bmp);
    using (g) {}
    

    Instead using (g) can be assignment "g = null" ? or statement "using" is assignment to null plus try-finally statement ?

    Sunday, December 25, 2011 10:00 AM

Answers

  • g = null can only make the object eligible for garbage collection but it doesn't call Dispose right away, it can take a while before this happens.

    "using" is indeed expanded to a try-finally:

    try { .... }

    finally { if (g != null) g.Dispose(); }

    • Marked as answer by Borneq Sunday, December 25, 2011 10:40 AM
    Sunday, December 25, 2011 10:07 AM

All replies

  • g = null can only make the object eligible for garbage collection but it doesn't call Dispose right away, it can take a while before this happens.

    "using" is indeed expanded to a try-finally:

    try { .... }

    finally { if (g != null) g.Dispose(); }

    • Marked as answer by Borneq Sunday, December 25, 2011 10:40 AM
    Sunday, December 25, 2011 10:07 AM
  • "g = null" not call Dispose?
    Sunday, December 25, 2011 10:40 AM
  • Nope.
    Sunday, December 25, 2011 11:06 AM
  • Hi,

    Also please always check the doc first. http://msdn.microsoft.com/en-us/library/yh598w02.aspx (using Statement) explains what is the underlying code generated by using this construct.


    Please always mark whatever response solved your issue so that the thread is properly marked as "Answered".
    Sunday, December 25, 2011 1:02 PM