Method returning DataTable with using

41,001

Solution 1

Yes, the DataTable will have been disposed when leaving the using block in GetDataTable.

Solution 2

Yes, the DataTable will be disposed when the code exit the using scope.

You should move the using to your main()

public static DataTable GetDataTable()
{
    DataTable dt = new DataTable()

    // fill DataTable logic
    return dt;
}

public void main()
{
  using(DataTable dt = GetDataTable())
  {
  // contine using dt
  }//here the table is disposed
}

Solution 3

you have to replace

public  void main()

to

public static void Main()

public static DataTable GetDataTable()
{
  using(DataTable dt = new DataTable())
  {
    // fill DataTable logic
    return dt;
  }
}

once your code leave GetDataTable dt will be disposed. Because using calls IDisposible

Share:
41,001
Theofanis Pantelides
Author by

Theofanis Pantelides

Updated on November 29, 2020

Comments

  • Theofanis Pantelides
    Theofanis Pantelides over 3 years

    Consider the following example:

    public static DataTable GetDataTable()
    {
        using(DataTable dt = new DataTable())
        {
            // fill DataTable logic
            return dt;
        }
    }
    
    public void main()
    {
        DataTable dt = GetDataTable();
    
        // contine using dt
    }
    

    Should I expect dt to be usable in main(), or was the DataTable disposed of in GetDataTable()?