Function that returns a datatable
When a function returns a datatable, does it just return a pointer to a datatable? I mean is the below example, which method to load a DataGrid would be better (1 or 2)? Are both equally efficient and accepted use of a function and datatable? (using pseudo-code here)
Code:
Function GetData() as DataTable
Dim myDataTable as New DataTable
cn.Open()
rSQLReader = cmd.ExecuteReader
myDataTable.Load(rSQLReader)
cn.Close()
Return myDataTable
End Function
Sub LoadDataGrid1()
Dim dt as New DataTable
dt = GetData()
myDataGrid.DataSource = dt
End Sub
Sub LoadDataGrid2()
myDataGrid.DataSource = GetData()
End Sub
Re: Function that returns a datatable
Your first option is wrong. The first line creates a new DataTable object and assigns it to the 'dt' variable. It then discards that object without ever using it and replaces it with the one that was created and returned by the GetData method. The 'New' keyword is NOT part of a declaration. Do not use the 'New' keyword unless you specifically want to create a new object. You obviously don't want to do that here because you are already getting an object from the GetData method. This:
vb.net Code:
Sub LoadDataGrid1()
Dim dt As DataTable
dt = GetData()
myDataGrid.DataSource = dt
End Sub
is the drawn-out equivalent of the second option. Note the absence of the 'New' keyword, so a variable is declared but no new object is created or assigned to it.
Re: Function that returns a datatable