Question

which approaches are correct about "using" (first or second)?

First:

using (DataTable dt = list.ToDataTable())
{
     dataList.DataSource = dt;
     dataList.DataBind();
}

Second:

 using (DataTable dt = list.ToDataTable())
 {
     dataList.DataSource = dt;
 }
 dataList.DataBind();
Was it helpful?

Solution

Well in your case it has to be the first approach otherwise you will dispose of the DataTable before it's been used (so DataBind() in the second would throw an exception).

In general though, you only need to keep code which uses the disposable object within the scope of the using.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top