none
Disposing of class instance RRS feed

  • Question

  • I created a utility class within my project which allows me to make database calls and other functions for my site.

    I create an instance of my class when my master page loads.  What I want to know is what do I need to add to my class to clean it up after my class instance is done being used?

    Thank you for any help you can give me.

    Wednesday, April 23, 2014 6:23 PM

Answers

  • If the class has references to disposable objects then you should implement IDisposable and dispose those objects. Otherwise there's nothing you need to do.

    If you don't intend to derive from the utility class then you could simply cleanup in the Dispose method:

    class Utility : IDisposable {
        SqlConnection conn;
        ...
        public void Dispose() {
            if (conn != null) {
                conn.Dispose();
                conn = null;
            }
        }
    }
    
    If you need to derive from this class then you need to use the dispose pattern to be able to cleanup objects referenced by the derived class.

    Of course, just implementing IDisposable is of no use is nothing calls Dispose. Normally you'd use a 'using' block for this but in your case you probably need to call Dispose from a page event, probably from Unload.

    Thursday, April 24, 2014 6:03 AM
    Moderator

All replies

  • If the class has references to disposable objects then you should implement IDisposable and dispose those objects. Otherwise there's nothing you need to do.

    If you don't intend to derive from the utility class then you could simply cleanup in the Dispose method:

    class Utility : IDisposable {
        SqlConnection conn;
        ...
        public void Dispose() {
            if (conn != null) {
                conn.Dispose();
                conn = null;
            }
        }
    }
    
    If you need to derive from this class then you need to use the dispose pattern to be able to cleanup objects referenced by the derived class.

    Of course, just implementing IDisposable is of no use is nothing calls Dispose. Normally you'd use a 'using' block for this but in your case you probably need to call Dispose from a page event, probably from Unload.

    Thursday, April 24, 2014 6:03 AM
    Moderator
  • Hi Shreeharsh,

    Thank you for your reply. 

    I currently have

    public class Utility {

    at the top of my class.  If I wanted to create a dispose function to clean up the connections and commands that are created should I put :IDisposable after "Utility"?  with this effect my other functions? 

    Thank you

    Thursday, April 24, 2014 12:44 PM
  • "should I put :IDisposable after "Utility"?"

    Yes, that's how interfaces are implemented.

    "with this effect my other functions?"

    No.

    Thursday, April 24, 2014 12:56 PM
    Moderator