To Dispose or Close, is there a difference?

I’m in the giving mood tonight so figured I would fire off one more post before I hit the sack. Last Summer Maurice Prather wrote an entry about when to use Dispose (and leveraging the using clause). This also led to a KB article about this, so check it out if you’re interested.

One thing that a few people have asked me is what’s the difference between calling Dispose or Close? Various blogs mention using either but is there a difference when it comes to an SPSite or SPWeb? Yes, there’s a difference so now that you’ve decided to use Dispose/Close to dump your objects, which one should it be?

Dispose is a virtual method on both the SPSite and SPWeb classes. That means you can override it and, in turn, call the base class if desired. Let’s say you have a complicated setup where mutiple webs are connected, or perhaps you’re calling an external web service. You could subclass SPWeb into your own class and have it handle those external connections. Then in your own SPWeb class you would override Dispose, clean up any external connections and extra stuff you have, and then call the base implementation of Dispose (which just in turn calls Close). Or you could call Close yourself in your own Dispose method. The Close method on the other hand is not virtual so you can’t override it. It’s the one that actually does the final cleanup for an SPWeb and SPSite object.

So basically, if you’re creating your own SPWeb or SPSite sub-class (and you’re perfectly okay to do this) and have to do extra cleanup that the base class wouldn’t know about (maybe connections to a SQL database, but not the SharePoint one right…) then override Dispose, do your stuff, and call the base implementation. Otherwise if you’re just using the classes normally you can call the Close method directly.

P.S. I would provide code for this but my plugin is broken for some reason (I blame my IE7 fiasco) but you guys are smart so you’ll figure it out.

1 Comment

  • Hi Bill,



    I would always call Dispose since you have to ensure that Close is called in an event of an exception, second if a class implements the IDisposable interface you are supposed to call Dispose on it ;)



    So if you are using Close your code will look something like this:



    SPSite site = null;

    SPWeb web = null;

    try

    {

    site = new SPSite(xyz);

    web = site.OpenWeb();// accuire

    // do stuff with web

    }

    finally

    {

    if( web != null )

    {

    web.Close();

    web.Dispose(); // in theory

    }

    if( site != null )

    {

    site.Close();

    site.Dispose(); // in theory

    }

    }



    Compared to this:



    using( SPSite site = new SPSite(xyz) )

    {

    using( SPWeb s = site.OpenWeb() )

    {

    }

    }



    The compiler will expand the using statement to a try finally block for us.



    IMHO cleaner code.



    Thanks

    /Jonas Nilsson

Comments have been disabled for this content.