Proper use of SPSite and SPWeb in code

Jul 25, 2008 at 9:21 PM
Nice little app. Thanks!

One thing:  Since SPSite and SPWeb are COM objects they need to be Disposed properly in code.

Here is the way it should look, for example:

                    using (SPSite spSite = new SPSite(_SPSiteURL))
                    {
                        using (SPWeb spWeb = spSite.OpenWeb())
                        {
                            SPList spList = spWeb.Lists[cmbxList.Text.Trim()];
                            DataTable dt = spList.Items.GetDataTable();
                            if (dt != null)
                            {
                                _ds.Tables.Add(dt);
                                _ds.AcceptChanges();

                                //bind dataset to grid...
                                dgResults.Visible = true;
                                dgResults.DataSource = dt;
                                btnExportXML.Enabled = true;
                            }
                        }
                    }
 
Setting spSite and spWeb = null doesn't really do anything useful. When the 'using' block exits the objects are disposed and the Garbage Collector takes care of them.