Theofanis Pantelides
Theofanis Pantelides

Reputation: 4854

Method returning DataTable with using

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()?

Upvotes: 3

Views: 48950

Answers (4)

    public DataTable GetValue(string name)
    {
        string connection = @"Data Source=DESKTOP-M5TQV9A;Initial Catalog=ALLTEST;Integrated Security=True";
        DataTable dt;
        SqlConnection con = new SqlConnection(connection);
        con.Open();
        using (SqlCommand cmd = new SqlCommand("up_searchUsers", con))
        {
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add("@SearchName", SqlDbType.VarChar).Value = name;
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            dt = new DataTable();
            da.Fill(dt);
            con.Close();
            return dt;
        }
    }

search in the textbox then get your results! :) Happy C# Codding

dataGridView1.DataSource = GetValue(textBox1.Text);

Upvotes: 0

il_guru
il_guru

Reputation: 8508

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
}

Upvotes: 5

anishMarokey
anishMarokey

Reputation: 11397

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

Upvotes: 2

LukeH
LukeH

Reputation: 269428

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

Upvotes: 7

Related Questions