Search code examples
c#datasetdisposing

using Multiple using statements to dispose DataSet and DataTables


Can you please explain what is happening here?

using(DataSet ds = GetDataSet()) // will this get disposed? if yes (when?)
{
    using(DataTable dt = ds.Tables[0]) /* in this line is ds available for dt? i found some issue with this kind of statement. dt gets null after this line */
    {
          // i know that ds is available here.
          //some code
    }
}

Solution

  • using(DataSet ds = GetDataSet()){
    
      using(DataTable dt = ds.Tables[0])
      // dt will be NULL if there are no tables in ds
      {
        // both dt & ds will be available here
    
      }// dt will get disposed
    
    }// ds will be disposed at this point...
    

    The equivalent code for this is:

    try{
     DataSet ds = GetDataSet();
     try{
      DataTable dt = ds.Tables[0];
      // dt will not be null if there are any tables in ds
      // Both ds & dt available here...
     }
     finally{
      dt.Dispose();
     }
    }
    finally{
     ds.Dispose();
    }