CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Sep 2008
    Posts
    90

    Question Is disposing a local brush variable necessary?

    MSDN recommends disposing any variable of type System.Drawing.Brush before its last reference is released. Otherwise, the resources it is using will not be freed until the garbage collector calls the Brush object's Finalize method.

    As we know, local variables are destroyed automatically when the control flow goes out of the scope of the method it belongs. So, is it necessary to dispose a brush object every time if it is local?

  2. #2
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: Is disposing a local brush variable necessary?

    Just wrap the usage of the brush inside a 'using' block instead of explicitly calling .Dispose().

    As far as 'needing' to do this.. Consider asking the same question with regard to a database connection. Technically, the connection will be closed when the gc runs. However, the gc doesn't immediately execute and clean up (even local out of scope variables) so you can actually run out of available db connections.

    The best practice is to wrap anything that holds onto a handle in a using block to immediately free the resource. In short, anything that implements idisposable wrap in a using block.
    Last edited by Arjay; November 9th, 2013 at 03:01 PM.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured