Using Statement When Returning Data

I use Memory Managementby returning data as shown below.

private DataSet ReturnDs()
{
    using (DataSet ds = new DataSet())
    {
        return ds;
    }
}

Request . Is there a problem when placing the "Use" operator when returning data? Am I still getting the full schema as well as the data in the receive function?

+5
source share
5 answers

This is definitely the wrong template. The only reason he is working right now is because he DataSet.Dispose()is actually a mannequin.

using (DataSet ds = new DataSet())
{
    return ds;
}  // there is a ds.Dispose() here but it does nothing.

If you replace the DataSet with, for example, the Enitity DbContext framework, then you will not see any data in the calling function.

+4
source

, , , : , yo .

: Dispose(), : using , . : . , API.

, , . , ? - :

SomeType foo = null;
try {
    // initialize and populate foo - this could error half-way through
    return foo;
} catch {
    if(foo != null) foo.Dispose();
    throw;
}

.

+4

using , , .

public void Caller()
{
  using(DataSet ds = GetDataSet())
  {
    // code here
  }
}

public DataSet GetDataSet()
{
  // don't use a using statement here
  return ds;
}

using , :

DataSet ds = null;
try
{
  // code here
}
finally
{
  if(ds != null)
  {
    ds.Dispose();
    ds = null;
  }
}

, using , using, Disposed (.. , ..), , . , , IDisposable . , , , Stream, .

, finally . , IDispoable . using, using, , , , , . Microsoft DataSet , - , .

+2

, .

-, ds.Dispose().

This means that the DataSet returned by your method will already be deleted when your call method receives it.

0
source

as a comment by Mert, note that you are deleting the object you are returning. but basically, use is actually an attempt / final, and dispose will be called the return method. The effect depends on the implementation of IDisposable for each type. usually you should not dispose of (kill) the entity that you return to the caller, which is likely to use it.

0
source

All Articles